The code given below, save a posted file with following validation check
{
string fileName = fuFile.PostedFile.FileName;
string fileExtension=System.IO.Path.GetExtension(fileName);
string fileMimeType = fuFile.PostedFile.ContentType;
int fileLengthInKB = fuFile.PostedFile.ContentLength / 1024;
string[] matchExtension = { ".jpg", ".png", ".gif" };
string[] matchMimeType = { "image/jpeg", "image/png", "image/gif" };
if (fuFile.HasFile)
{
if (matchExtension.Contains(fileExtension) && matchMimeType.Contains(fileMimeType))
{
if (fileLengthInKB <= 1024)
{
fuFile.SaveAs(Server.MapPath(@"UserImages/" + fileName));
Response.Write("File Uploaded Successfully");
}
else
{
//Please choose a file less than 1MB
}
}
else
{
//Please choose only jpg, png or gif file.
}
}
else
{
//Please choose a file.
}
}
Aspx :-
<asp:FileUpload runat="server" ID="fuFile" />
<asp:Button runat="server" ID="btnUpload" Text="Upload" onclick="btnUpload_Click"/>
- Posted data must contain a file (posted file must be exist)
- Extension must be .jpg, .png or .gif
- Mime Type (Content Type) must be image/jpeg, image/png or image/gif
- Size of file must be less than 1MB
{
string fileName = fuFile.PostedFile.FileName;
string fileExtension=System.IO.Path.GetExtension(fileName);
string fileMimeType = fuFile.PostedFile.ContentType;
int fileLengthInKB = fuFile.PostedFile.ContentLength / 1024;
string[] matchExtension = { ".jpg", ".png", ".gif" };
string[] matchMimeType = { "image/jpeg", "image/png", "image/gif" };
if (fuFile.HasFile)
{
if (matchExtension.Contains(fileExtension) && matchMimeType.Contains(fileMimeType))
{
if (fileLengthInKB <= 1024)
{
fuFile.SaveAs(Server.MapPath(@"UserImages/" + fileName));
Response.Write("File Uploaded Successfully");
}
else
{
//Please choose a file less than 1MB
}
}
else
{
//Please choose only jpg, png or gif file.
}
}
else
{
//Please choose a file.
}
}
Aspx :-
<asp:FileUpload runat="server" ID="fuFile" />
<asp:Button runat="server" ID="btnUpload" Text="Upload" onclick="btnUpload_Click"/>