In web开发者_JAVA技巧 application how to restrict the uploaded file types when opening file upload dialog. If you are using ASP.NET & c#
Just validate the file extension as i did for excel file
string fileExtension = Path.GetExtension(fileUpload.PostedFile.FileName.ToString());
//if (fileExtension == ".xls" || fileExtension == ".xlsx")
if (fileExtension == ".xls")
{
return true;
}
else
{
return false;
}
You can use the "accept" attribute from normal HTML input type="file"
http://www.w3schools.com/jsref/dom_obj_fileupload.asp
First use the accept attribute in the HTML.
Then check the ContentType of the file.
(DO not check the name of the file, this is the web not a local machine, so you don't know what way people name files, especially on systems that differ from windows in the way they determine file types, or which has different bindings between extensions and applications to yours)
Finally, if it's possible to detect a mis-reported file (attempting to load it into a relevant class - such as loading an image/png into a Bitmap - looking for defined file "magic numbers" in the first few bytes, etc.) then do that too. The magic numbers approach can be useful (do not confuse with the advice to use constants to avoid "magic numbers" in source code, different meaning) as many file types must start with a sequence of bytes that matches a particular pattern. E.g. if someone uploads random garbage claiming it's a PNG or a GIF you can detect that after looking at just the first few bytes.
精彩评论