I have added a file upload to my asp.net website. However, I want to limit the file types that user can select. For example, I only the user to select mp3 files. How can I a
I have a similar application that is being used to upload PDF files. While it would be great if the Upload Control had a file type filter out of the box, I found it wouldn't really solve the problem of limiting the file type to upload.
For instance, if a user were to simply rename a Word document from "myfile.docx" to "myfile.pdf" the system would assume it was a valid file, even though the actual file encoding is invalid; this would cause issues in other parts of the application.
To actually solve the issue, you can take the byte array from the control and parse it as a string. Then apply a filter. Here is the code I have:
private static void CheckForValidFileType(byte[] data)
{
var text = ASCIIEncoding.ASCII.GetString(data);
if (!text.StartsWith("%PDF"))
throw new Exception("Invalid file type selected.");
}
Of course you will need to know what patterns are valid for your file type, and may want to use a RegEx instead of the .Net string helper method, but the general idea is to actually check the actual file contents and not rely on the file extension for validation.
Ryan A.