Web developers wiki ASP.NET Sitecore Sharepoint Kentico by Evident Interactive

Usually the ASP.NET FileUpload control is used when a user needs to upload a file to the server. By default the FileUpload control allows the user to select any type of file to upload. This can cause problems when a user is only allowed to upload an image.

There are several methods to check if the file that is sent to the server is an image, a few examples:
- Check the extension of the posted file
- Check the ContentType of the posted file

However, both methods are not very safe. The (probably) easiest way to validate a posted file, is trying to create an System.Drawing.Image object from it.

        protected void ValidateImage(object source, ServerValidateEventArgs args)
        {
            System.Drawing.Image img = null;
            try
            {
                img = System.Drawing.Image.FromStream(FileUploadImage.PostedFile.InputStream);
            }
            catch (Exception ex)
            {
                //Uploaded file is not an image, get localized errormessage from somewhere
                this.CustomValidatorImage.ErrorMessage = Helpers.GetInvalidImageMessage() ;

                args.IsValid = false;
                return;
            }
	}

Once the posted file is a verified image, it is possible to take the image filter a step further by only allowing

certain image types. This can be done by testing the RawFormat property of a System.Drawing.Image object.

if (img.RawFormat.Guid == System.Drawing.Imaging.ImageFormat.Jpeg.Guid)
{
	//do something with the Jpeg
}

if (img.RawFormat.Guid == System.Drawing.Imaging.ImageFormat.Png.Guid)
{
	//do something with the Png
}

 © Evident Interactive BV