How to specify file extension in ASP.Net upload control?
Is there a way to sp开发者_JS百科ecify a file extension for ASP.NET upload control? E.g. I want to upload images with jpg and png extensions only.
I can implement this easily for a windows application, but struggling with ASP.Net
Thank you
string[] validFileTypes = { "bmp", "jpg", "png" };
string ext = Path.GetExtension(fileUpload1.FileName);
bool isValidType = false;
for (int i = 0; i < validFileTypes.Length; i++)
{
if (ext == "." + validFileTypes[i])
{
isValidType = true;
break;
}
}
if (!isValidType)
{
lblMessage.Text = "Invalid File Type";
}
else
{
lblMessage.Text = "File Uploaded Successfullty";
}
You can use Javascript to check whether the filename ends with a particular extension, but this doesn't prevent someone renaming any type of file to be .jpg or .png...so you would want to confirm the actual type of file on the server...
The client-side png and jpg check will help in most cases to prevent a wasted upload though...
Simplified using LINQ / Lambda:
string ext = Path.GetExtension(fileUpload1.FileName);
string[] validFileTypes = { "bmp", "jpg", "jpeg", "png" };
bool isValidType = validFileTypes.Any(t => ext == "." + t);
if(isValidType)
'do something
If you use Flash, then you could define the file type (obviously this does not help if someone changes the file ending).
We are using NeatUpload and that has worked well for years:
http://neatupload.codeplex.com/
There is a setting for the filetype.
精彩评论