How to get more information from a InputStremed file? - asp.net-mvc-3

If I'm using the InputStream to receive a file, like
HttpContext.Current.Request.InputStream
How can get more information about the file?
I can easily convert a Stream into a phisical File, but for example, how would I know the file extension in use?
string fileIn = #"C:\Temp\inputStreamedFile.xxx"; // What extension?
using (FileStream fs = System.IO.File.Create(fileIn))
{
Stream f = HttpContext.Current.Request.InputStream;
byte[] bytes = new byte[f.Length];
f.Read(bytes, 0, (int)f.Length);
fs.Write(bytes, 0, bytes.Length);
}
The idea behind this is because using HttpPostedFileBase I always get null:
public ContentResult Send(HttpPostedFileBase fileToUpload, string email)
{
// Get file stream and save it
// Get File in stream
string fileIn = Path.Combine(uploadsPath, uniqueIdentifier),
fileOut = Path.Combine(convertedPath, uniqueIdentifier + ".pdf");
// Verify that the user selected a file
if (fileToUpload != null && fileToUpload.ContentLength > 0)
{
// extract only the fielname
string fileExtension = Path.GetExtension(fileToUpload.FileName);
fileIn = String.Concat(fileIn, fileExtension);
fileToUpload.SaveAs(fileIn);
}
// TODO: Add Convert File to Batch
return Content("File queued for process with id: " + uniqueIdentifier);
}
and this is what I'm sending from the command line:
$ curl --form email='mail#domain.com' --form fileToUpload='C:\temp\MyWord.docx' http://localhost:64705/send/
File queued for process with id: 1d777cc7-7c08-460c-8412-ddab72408123
the variable email is filled up correctly, but fileToUpload is always null.
P.S. This does not happen if I use a form to upload the same data.

I'm sorry if this doesn't help, but why use InputStream to get uploaded file(s) ?
This is what I usually do:
[HttpPost]
public ActionResult Upload(HttpPostedFileBase[] files) {
String physicalPath = "c:\\whatever";
foreach (var file in files) {
String extension = Path.GetExtension(file.FileName);
file.SaveAs(physicalPath + "\\" + file.FileName);
}
return View();
}

The only problem I found was using curl... I was forgetting the # sign that mention that the uploaded form would be encoded as multipart/form-data.
The correct curl command to use HttpPostedFileBase would be:
$ curl --form email='mail#domain.com'
--form fileToUpload=#'C:\temp\MyWord.docx'
http://localhost:64705/send/

You can get the info about posted file from <input type="file" />. But actually it's used a bit different way to upload files in asp.net mvc check out here

Related

How to create a string for #Html.ActionLink that concatenates an integer from the Model and a string

I'm using VS2015, MVC 5 design model. Creating a link that says "View" to open a PDF file in a new browser tab. It works fine, but the document sub-directory is hard-coded in the controller. I need to pass the document sub-directory + filename to the controller. The document sub-directory is the same as the Model.id . I'm having a difficult time converting the Model.id to a string and concatenating with the filename.
The following code in the view works fine with the hard-coded sub-directory in the controller
<td>#Html.ActionLink("View", "ViewAttachedDoc", "Documents", new { filename = item.filename}, new { target = "_blank" })</td>
But this code does not work
<td>#Html.ActionLink("View", "ViewAttachedDoc", "Documents", new { filename = Convert.ToString(Model.id) + "\" + item.filename }, new { target = "_blank" })</td>
The controller action is:
public FileResult ViewAttachedDoc(string filename)
{
string DocPath = ConfigurationManager.AppSettings["DocPath"];
string path = Path.Combine(DocPath, filename);
return File(path, "application/pdf");
}
TIA,
Tracy
The issue is likely from trying to pass a backslash through the URL. This link of a similar question has that same problem and their solution was to use HttpUtility.UrlEncode(value); and HttpUtility.UrlDecode(value);. Otherwise if that still doesn't work, what error are you getting?
P.S. C# automatically converts / -> \ for retrieving files.

File extension for tab-delimited values that can be opened by Excel?

I'm outputting a tab-delimited file from my webapp that should be opened in Excel. The problem is that .xls seems not good for opening and editing it, then Excel required some other format, and if I change the extension to .tsv then the file becomes unknown for Excel (on Windows 7) and .csv is for comma-separated. Can you advice me which the file extension should be?
This is the code that outputs the file and it works. It's just that I should choose the most suitable extension for tab-separated values.
#RequestMapping(value = "/export", method = RequestMethod.GET)
#ResponseBody
public ModelAndView export(HttpServletResponse response) {
try {
String str = "";
Iterator<Individual> iterator = customerAccountService.getAllIndividuals().iterator();
while(iterator.hasNext()){
Individual individual = iterator.next();
str = str + individual.getId() + "\t" +individual.getIndividualName().getName() + "\t" + individual.getAddress().getStreetName() + "\n";
}
InputStream is = new ByteArrayInputStream(str.getBytes());
IOUtils.copy(is, response.getOutputStream());
response.setContentType("application/xls");
response.setHeader("Content-Disposition","attachment; filename=export.tsv");
response.flushBuffer();
} catch (IOException ex) {
//logger.info("Error writing file to output stream. Filename was '" + fileName + "'");
throw new RuntimeException("IOError writing file to output stream");
}
ModelAndView modelAndView = new ModelAndView(ViewName.MENU);
modelAndView.addObject(ObjectName.ADD_FORM, new LoginForm());
return modelAndView;
}
Put
sep=\t
as the first line in your .csv-file (yes, you can name it .csv then). That tells excel what the delimiter character should be.
Note, that actually if you open the .csv with a text editor, it should read like
sep= (an actual tabulator character here, it's just not visible...)

Upload a image in a porltet Liferay

I am doing a portlet to create banners. I preferences I made the form with: input type="file" and the form nctype='multipart/form-data'
In the processAction I get the image, but I don't know how save it in the server, because I only get save in temporal instance portlet, but if I restart the server I lose the image.
This is my code to save the image:
private boolean uploadFile( ActionRequest request, ActionResponse response) throws ValidatorException, IOException, ReadOnlyException {
try {
// Si la request es del tipo multipart ...
if (PortletFileUpload.isMultipartContent(request)) {
DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
PortletFileUpload servletFileUpload = new PortletFileUpload(diskFileItemFactory);
servletFileUpload.setSizeMax(81920); // bytes
List fileItemsList = servletFileUpload.parseRequest(request);
Iterator it = fileItemsList.iterator();
while (it.hasNext()){
FileItem fileItem = (FileItem)it.next();
if (fileItem.isFormField()){
}
else{
String nombreCampo = fileItem.getFieldName();
String nombreArchivo = fileItem.getName();
String extension = nombreArchivo.substring(nombreArchivo.indexOf("."));
PortletContext context = request.getPortletSession().getPortletContext();
String path = context.getRealPath("/images");
File archivo = new File(path + "/" + nombreArchivo);
PortletContext pc = request.getPortletSession().getPortletContext();
fileItem.write(archivo);
}
}
}
} catch (Exception e) {}
return true;
}
I don't know if I am doing something wrong or this isn't the correct way.
Any idea?
Thanks in advance
EDIT:
Finally I tried do it with DLFolderLocalServiceUtil and DLFileEntryLocalServiceUtil, but it doesn't work correctly. When I load the page you can see the image, but after, when the page is load completely, the image disappears.
I don't know if it is because I don't create fine the fileEntry or the url is wrong.
This is my code:
long folderId = CounterLocalServiceUtil.increment(DLFolder.class.getName());
DLFolder folder = DLFolderLocalServiceUtil.createDLFolder(folderId);
long userId = themeDisplay.getUserId();
long groupId = themeDisplay.getScopeGroupId();
folder.setUserId(userId);
folder.setGroupId(groupId);
folder.setName("Banner image " + nombreArchivo+String.valueOf(folderId));
DLFolderLocalServiceUtil.updateDLFolder(folder);
ServiceContext serviceContext= ServiceContextFactory.getInstance(DLFileEntry.class.getName(), request);
File myfile = new File(nombreArchivo);
fileItem.write(myfile);
List<DLFileEntryType> tip = DLFileEntryTypeLocalServiceUtil.getFileEntryTypes(DLUtil.getGroupIds(themeDisplay));
DLFileEntry DLfileEntry = DLFileEntryLocalServiceUtil.addFileEntry(userId, groupId, 0, folderId, null, MimeTypesUtil.getContentType(myfile), nombreArchivo, "Image banner_"+nombreArchivo, "", tip.get(0).getFileEntryTypeId(), null, myfile, fileItem.getInputStream(), myfile.getTotalSpace(), serviceContext);
FileVersion fileVersion = null;
//FileEntry fileEntry = DLAppServiceUtil.getFileEntry(groupId, folderId, nombreArchivo);
//String path = DLUtil.getPreviewURL(fileEntry, fileVersion, themeDisplay, "&imagePreview=1");
String path1 = themeDisplay.getPortalURL()+"/c/document_library/get_file?uuid="+DLfileEntry.getUuid()+"&groupId="+themeDisplay.getScopeGroupId();
String path = "/documents/" + DLfileEntry.getGroupId() + "/" + DLfileEntry.getFolderId() + "/" + DLfileEntry.getTitle()+"/"+DLfileEntry.getUuid();
System.out.println("path " + path);
System.out.println("path " + path1);
prefs.setValue(nombreCampo, path);
And this is the output:
path /documents/10180/0/cinesa888.png/f24e6da2-0be8-47ad-a3b5-a4ab0d41d17f
path http://localhost:8080/c/document_library/get_file?uuid=f24e6da2-0be8-47ad-a3b5-a4ab0d41d17f&groupId=10180
I tried to get the url like lpratlong said (DLUtil) but when I tried to get the FileEntry with DLAppServiceUtil.getFileEntry(..) I have an error that says no exist FileEntry.
I don't know what I am doing wrong.. Any idea?
Thanks.
You can use Liferay API to store the file in the Document Library : take a look in DLFolder and DLFileEntry API (for exemple, DLFileEntryLocalServiceUtil will show you allowed local operations).
These API will allowed you to store your file in your file system (in the "data" folder of your Liferay installation) and to store reference of your file in Liferay database.

How to retrieve photo previews in app.net

When I have an app.net url like https://photos.app.net/5269262/1 - how can I retrieve the image thumbnail of the post?
Running a curl on above url shows a redirect
bash-3.2$ curl -i https://photos.app.net/5269262/1
HTTP/1.1 301 MOVED PERMANENTLY
Location: https://alpha.app.net/pfleidi/post/5269262/photo/1
Following this gives a html page that contains the image in a form of
img src='https://files.app.net/1/60621/aWBTKTYxzYZTqnkESkwx475u_ShTwEOiezzBjM3-ZzVBjq_6rzno42oMw9LxS5VH0WQEgoxWegIDKJo0eRDAc-uwTcOTaGYobfqx19vMOOMiyh2M3IMe6sDNkcQWPZPeE0PjIve4Vy0YFCM8MsHWbYYA2DFNKMdyNUnwmB2KuECjHqe0-Y9_ODD1pnFSOsOjH' data-full-width='2048' data-full-height='1536'
Inside a larger block of <div>tags.
The files api in app.net allows to retrieve thumbnails but I somehow don't get the link between those endpoints and above urls.
The photos.app.net is just a simple redirecter. It is not part of the API proper. In order to get the thumbnail, you will need to fetch the file directly using the file fetch endpoint and the file id (http://developers.app.net/docs/resources/file/lookup/#retrieve-a-file) or fetch the post that the file is included in and examine the oembed annotation.
In this case, you are talking about post id 5269262 and the URL to fetch that post with the annotation is https://alpha-api.app.net/stream/0/posts/5269262?include_annotations=1 and if you examine the resulting json document you will see the thumbnail_url.
For completeness sake I want to post the final solution for me here (in Java) -- it builds on the good and accepted answer of Jonathon Duerig :
private static String getAppNetPreviewUrl(String url) {
Pattern photosPattern = Pattern.compile(".*photos.app.net/([0-9]+)/.*");
Matcher m = photosPattern.matcher(url);
if (!m.matches()) {
return null;
}
String id = m.group(1);
String streamUrl = "https://alpha-api.app.net/stream/0/posts/"
+ id + "?include_annotations=1";
// Now that we have the posting url, we can get it and parse
// for the thumbnail
BufferedReader br = null;
HttpURLConnection urlConnection = null;
try {
urlConnection = (HttpURLConnection) new URL(streamUrl).openConnection();
urlConnection.setDoInput(true);
urlConnection.setDoOutput(false);
urlConnection.setRequestProperty("Accept","application/json");
urlConnection.connect();
StringBuilder builder = new StringBuilder();
br = new BufferedReader(
new InputStreamReader(urlConnection.getInputStream()));
String line;
while ((line=br.readLine())!=null) {
builder.append(line);
}
urlConnection.disconnect();
// Parse the obtained json
JSONObject post = new JSONObject(builder.toString());
JSONObject data = post.getJSONObject("data");
JSONArray annotations = data.getJSONArray("annotations");
JSONObject annotationValue = annotations.getJSONObject(0);
JSONObject value = annotationValue.getJSONObject("value");
String finalUrl = value.getString("thumbnail_large_url");
return finalUrl;
} .......

export chinese, japanese character in .csv file + mvc3

I am using following code to export the content to .cvs file
which also support chinese and japanese characters.
public ActionResult Download(strng accnumber)
{
string csvContent = "东西,东西,东西, hi";
var data = Encoding.UTF32.GetBytes(csvContent );
string filename = "CSV_" + accnumber + ".csv";
return File(data, "text/csv", filename);
}
when i export my file i am not getting proper chinese or japanese characters. what is missing?
i have used UTF32 encoding to support it.
Edited:
i have noticed that opening my .csv file in notepad shows perfect characters but ms-excel doesn't.
I am also got same problem, solve it by using UTF-8-BOM.
Encoding.UTF8.GetPreamble().Concat(Encoding.UTF8.GetBytes(stringData)).ToArray()
As you are on asp.net serving that file you also have to deal with the encoding of the http pipleline. I din't spot that earlier, sorry.
Instead of having a plain ActionResult you should use one of the derived ActionResults, I've used FileContentResult. Please pay note to the special ContentType I'm constructing to tell the browsers an UTF-32 file is coming...
public ActionResult Download(string accnumber)
{
string csvContent = "东西,东西,东西, hi";
var data = Encoding.UTF8.GetBytes(csvContent);
// add byte order mark
var bom = new byte[] { 0xEF, 0xBB, 0xBF };
// hold it all
var all = new byte[bom.Length + data.Length];
// copy over BOM
Array.Copy(bom, all, bom.Length);
// copy over data
Array.Copy(data, 0, all, bom.Length, data.Length);
string filename = "CSV_" + accnumber + ".csv";
var file = new FileContentResult( all, "text/csv" )
{
FileDownloadName = filename
};
return file;
}
I encountered this problem too. I fix it by adding the following line just before "return file ;" and it works for me.
Response.Write("<meta http-equiv=Content-Type content=text/html;charset=utf-8>");
return file;

Resources