In my previous two examples, we have learned on how to Upload and Save the Image to a Folder and path to database and how to Save the Image to the Database. The two previous examples only tackle the basics about uploading and saving a file without validating the file to be uploaded. In this example, I’m going to show on how to validate a file that only allows image files to be uploaded using server side validations.
Here are the code blocks below:
private void StartUpLoad()
{
if (FileUpload1.HasFile)
{
HttpPostedFile postedFile = FileUpload1.PostedFile;
if (IsImageFile(postedFile))
{
//Save image here
}
else
{
Response.Write("Invalid File, Cannot Upload!");
}
}
else
{
Response.Write("Please select a File");
}
}
protected bool IsImageFile(HttpPostedFile file)
{
bool isImage = false;
System.IO.FileStream fs = new System.IO.FileStream(file.FileName, System.IO.FileMode.Open, System.IO.FileAccess.Read);
System.IO.BinaryReader br = new System.IO.BinaryReader(fs);
string fileclass = "";
byte buffer;
try
{
buffer = br.ReadByte();
fileclass = buffer.ToString();
buffer = br.ReadByte();
fileclass += buffer.ToString();
}
catch
{
return false;
}
finally
{
br.Close();
fs.Close();
}
/*extension lists with codes
*7173 gif
*255216 jpg
*13780 png
*6677 bmp
*239187 txt,aspx,asp,sql
*208207 xls.doc.ppt
*6063 xml
*6033 htm,html
*4742 js
*8075 xlsx,zip,pptx,mmap,zip
*8297 rar
*01 accdb,mdb
*7790 exe,dll
*64101 bat
*/
//only allow images jpg gif bmp png
String[] fileType = { "255216", "7173", "6677", "13780" };
for (int i = 0; i < fileType.Length; i++)
{
if (fileclass == fileType[i])
{
isImage = true;
break;
}
}
return isImage;
}
As you can see, we have checked the posted file of the FileUpload and pass it to the IsImageFile() method that returns a Boolean type for checking the actual type of the posted file. If the file contains image extension such as “jpg”, “gif”, “bmp” and “png” then it will return TRUE else it will return false.
That's it! Hope you will find this example useful!
Technorati Tags: ASP.NET,C#,TipsTricks,Image Uploading
