How to find file extension in Azure Storage? - asp.net

If there is no extension in the file name, then I cannot get the contentType to create FileStreamResult.
Example:
byte[] byteFile = await someDirectory.GetFileContentAsync(fileName);
string contentType;
new FileExtensionContentTypeProvider().TryGetContentType(fileName, out contentType); // fileName without extension
return (byteFile, contentType); // contentType == null
Is there a way to get the extension not from the name?

Looking at the code for FileExtensionContentTypeProvider, there's a predefined list of file extensions and their corresponding mime-types. TryGetContentType method will return null if the file extension is not in that list.
If you get a file without file extension, one possible way would be to find the kind of file by reading it's metadata but that's really complicated. For example, reading the file contents you can find out if the file is an image and if it is of type png. But you will need to write code to identify each type of image (png, bmp, gif etc.).
A simpler way would be to infer null content type as default content type. In case of Azure Storage, it will be application/octet-stream.

Related

FileResult not returning proper file type and file name

I have an ASP.NET MVC application with an ActionResult called GenerateReport. I'm trying to return a byte array to save an Excel file. Here are snippets:
var contentType = "application/vnd.ms-excel";
var fileName = "Statistics.xlsx";
...
var fileBytes = package.GetAsByteArray();
return File(fileBytes, contentType, fileName);
When I'm prompted to save the file, it sometimes (but not always) asks what I want to do with "GenerateReport". It's naming the file the same as the ActionResult and it's not giving it a file type. I will request to save it and it will say that it failed to save. I will select Retry and it will save fine. Then, if I rename it to an .xlsx, all of the data is there and correct. I'm using IE9 and Chrome and I haven't noticed it happen in Chrome. Unfortunately, it needs to work in IE9.
Does anyone know why it's not getting my content type and file name sometimes?
Check the response for Content-Encoding. It might be the same issue like here PHP File Serving Script: Unreliable Downloads?

Upload File with FileUpload and Stock in database using Framwork entity

I want to upload file with file upload and stock in DataBase SQLserver using framework entity , I use this code :
string strRealPath = Request.PhysicalApplicationPath;
if(FileUpload1.HasFile)
{
string fileName = FileUpload1.FileName;
FileUpload1.SaveAs(strRealPath + fileName);
//Now insert the file into the database.
}
f.photo = Convert.ToString(FileUpload1.FileBytes);
But I find anything added .I use the debugger he tell me that posted file is null
Thanks
Firstly, your form should be encrypted as multipart/form-data. Add parameter to your form tag like below:
enctype = "multipart/form-data"
Secondly you have to send file as controller parameter HttpPostedFile.
This tutorial will be useful for you. Let us know, does it work properly.
===EDIT===
When it comes to database. You have to have column of binary type (varbinary[max]), and you
should try save it there (remember about try/catch). To read content of the file, use stream reader.

asp.net image jpeg not saving correctly

I am trying to save a jpeg image in an uploads folder which has correct permissions setup. When I test the file is being saved (eg: images/uploads/Winter.jpg) but if I try to view the image in my browser or if I attempt to open the image using anything else the image does not display.
I think that the file is not being encoded correctly before saving it to disk but am not very experienced dealing with the saving of files, encoding. Does the below code look ok or do I need to encode the file being uploaded somehow before saving it to disk?
String imgPath = "newsletter\\images\\uploads\\";
String filename = System.IO.Path.GetFileName(upload.PostedFile.FileName);
filepath = imgPath + filename;
filepath = Request.PhysicalApplicationPath + filepath;
upload.PostedFile.SaveAs(filepath);
The file saves to the correct folder but is only 150bytes in size. If I try to browse to the file and view it with an image viewer it does not display correctly.
Encoding shouldn't be a problem - the raw data isn't changing. However, it's possible the browser isn't sending all the data, or that the upload control is deleting the data before you're saving it.
Make sure that you call .SaveAs() before the page begins unloading, and before any additional postbacks. I think we'll need to see more surrounding code to help further.
Another note - by allowing the existing file extension to be used, you're allowing users to upload .aspx files, which could subsequently be executed through a request. Safe filenames are GUIDs and whitelisted file extensions. Using un-sanitized uploaded path information is very dangerous. If you re-use filenames, sanitize them to alphanumerics.

Kentico - Pass MemoryStream file to MediaFileInfo API

I have created a iTextSharp PDF file that is created to a MemoryStream. But I now need to pass this file to the Kentico media library.
I would be grateful if anyone could show my how to do this. The code I have currently is:
//Media Library Info - takes Media Library Name and Website Name
MediaLibraryInfo libraryInfo = MediaLibraryInfoProvider.GetMediaLibraryInfo("MyLibrary", CMSContext.CurrentSiteName);
//Folder in Media Library where Item will be Inserted
string mediaLibraryFolder = folder;
//create media file info item - takes the relative path to the document, the library ID, and the folder name where the document will be located within the media library
MediaFileInfo fileInfo = new MediaFileInfo();
fileInfo.FileLibraryID = libraryInfo.LibraryID;
fileInfo.FileBinaryStream = file;
fileInfo.FileName = title.Replace(" ", "").Trim();
fileInfo.FileTitle = title;
fileInfo.FileDescription = description;
fileInfo.FileExtension = ".pdf";
fileInfo.FileMimeType = "application/pdf";
fileInfo.FilePath = String.Concat("/", folder, "/", title.Replace(" ", "").Trim(), ".pdf");
// Save media file info
MediaFileInfoProvider.ImportMediaFileInfo(fileInfo);
I keep getting database errors due to nullable columns e.g. FileSize, FileExtension, etc. Since I am using a MemoryStream I can't find a way to supply all that information.
Am I using the MediaFileInfo API incorrectly in conjunction with a MemoryStream file?
Actually, I don't think that you need to do anything that RadekM said. You can simply stream the file to disk to save it, and then call the import method you're using to import it into the media library.
For example, a Media Library called "Site Images" for the site "MySite" will have a folder on disk at /MySite/media/Site Images/. Drop your file into there (you can use sub folders if you want). At this point the file is "in" the media library, but it hasn't been imported yet, so you wont be able to use it. You can see this is true by viewing the Media Library in the CMS Desk interface. However, this file has not yet been imported into the Media Library and you should see an exclamation point inside a yellow triangle next to your new file.
So after you get the file in the right location, you can use that file information to populate the MediaFileInfo object and Import the file.
Could you adapt this code and pass the bytes of the PDF from here?
programmatically adding files to the Kentico Media Library
Regrettably, MemoryStream class does not contain these informations, so you can’t gain them from this object directly. Anyway, if you want to supply FileSize property, you can use ms.Length property as a workaround. Basically, this particular property is not important, so it can be even some dummy number.
As for extension – are you saying that you are receiving error saying this property is null, although you set it like „fileInfo.FileExtension = ".pdf";“? Can you clarify?
Also please note that you need to set some other properties, FileSiteID, FileCreatedWhen, FileGUID and FilePath (path inside given media library). If you have full source code of Kentico API, you can get an inspiration from constructor of MediaFileInfo object in \MediaLibrary\MediaFileInfo.cs class.

check uploaded file in vb.net

I need a snippet to check file for validity (I'm allowing users to upload xml files). So I need to check whether uploaded file is XML.
The best I can think of is just check if extension is ".xml". What if its replaced?
You can try loading it like this and catch the exception:
XDocument xdoc = XDocument.Load("data.xml"));
Presumably, if they're uploading XML, then you're going to use it for something afterwards. In this case you should validate the XML against a Schema (XSD etc) so that you know you aren't going to hit unexpected values/layouts etc.
In Urlmon.dll, there's a function called FindMimeFromData.
From the documentation
MIME type detection, or "data
sniffing," refers to the process of
determining an appropriate MIME type
from binary data. The final result
depends on a combination of
server-supplied MIME type headers,
file extension, and/or the data
itself. Usually, only the first 256
bytes of data are significant.
So, read the first (up to) 256 bytes from the file and pass it to FindMimeFromData.
If you must validate the xml (assuming you want to validate the entire thing) you can use the XmlDocument class and catch an exception if it's not XML.

Resources