That's pretty funny the FileUpload control's contentType can lie to you. I guess it just loads the file into a byte[] and let's you take it from there.
I think you can test the real file contents information by loading the file into a System.Drawing.Image and testing it's RawFormat property. There, you will find a Guid that is unique for each image type. If you can't load the file into an Image, I guess it's
not a jpg, png or gif as you requested.
Zeerover
Member
7 Points
13 Posts
Re: Fileupload: allow only .jpg .gif and .png
Jul 09, 2008 11:02 AM|LINK
That's pretty funny the FileUpload control's contentType can lie to you. I guess it just loads the file into a byte[] and let's you take it from there.
I think you can test the real file contents information by loading the file into a System.Drawing.Image and testing it's RawFormat property. There, you will find a Guid that is unique for each image type. If you can't load the file into an Image, I guess it's not a jpg, png or gif as you requested.
System.Drawing.Image img = System.Drawing.Image.FromStream(FileUpload1.PostedFile.InputStream);
if (img.RawFormat.Guid == System.Drawing.Imaging.ImageFormat.Jpeg.Guid) {do something}
Or, if you want to return the type of the image, try this:
public static string MimeType(System.Drawing.Image imgPhoto)
{
foreach (ImageCodecInfo codec in ImageCodecInfo.GetImageDecoders())
{
if (codec.FormatID == imgPhoto.RawFormat.Guid)
return codec.MimeType;
}
return "image/unknown";
}