aibip:
I see many tutorials expainging cliant side validation, but I'm not sure what is the best way to validate image file in server side.
I have this upload script, but I would like to allow only image files.
Could you show me how to add validation? (or link to web site )
Hi,
Here is way to detect the real extension of files. Please have a try at the demo below. It runs a function called IsAllowedExtension to judge if the uploaded is an image. Also, it can detect other kinds of files according to the file list in the comments.
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (FileUpload.HasFile)
{
HttpPostedFile upFile = FileUpload.PostedFile;
if (IsAllowedExtension(upFile))
{
upFile.SaveAs("path");
}
}
}
protected bool IsAllowedExtension(HttpPostedFile file)
{
bool ret = false;
System.IO.FileStream fs = new System.IO.FileStream(file.FileName, System.IO.FileMode.Open, System.IO.FileAccess.Read);
System.IO.BinaryReader r = new System.IO.BinaryReader(fs);
string fileclass = "";
byte buffer;
try
{
buffer = r.ReadByte();
fileclass = buffer.ToString();
buffer = r.ReadByte();
fileclass += buffer.ToString();
}
catch
{
return false;
}
r.Close();
fs.Close();
/*extension list for files
*
*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])
{
ret = true;
break;
}
}
return ret;
}
If I have misunderstood you, please feel free to let me know.
Best Regards,
Shengqing Yang
Please remember to click “Mark as Answer” on the post that helps you, and to click “Unmark as Answer” if a marked post does not actually answer your question. This can be beneficial to other community members reading the thread : )