AspAlliance.com LogoASPAlliance: Articles, reviews, and samples for .NET Developers
URL:
http://aspalliance.com/articleViewer.aspx?aId=781&pId=-1
CodeSnip: Validate Image Size, Dimension, and Type Uploads
page
by Steven Swafford
Feedback
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 21463/ 16

Introduction

Do you allow your users to upload images?  If so, would you like to place some restrictions on the size, dimensions, and type of image that is acceptable?  Accomplishing this is much easier than you may think.

Let us say we have the following business rules that we need to enforce:

1.      Image must be either a GIF or JPG.

2.      Image can be no larger than 512KB.

3.      Image dimensions can be no greater than 600x600.

By enforcing such rules we can then prevent those rogue users who may want to eat up the file system space.

Implementation

Create a new web form named Upload.aspx and add an HTML input tag to it.  Be sure to add runat="server" to this tag:

Listing 1

<input id="FileUpload" type="file" name="FileUpload" runat="server">

Next in the code-behind add the following piece of code:

Listing 2

protected HtmlInputFile FileUpload;

Next we need to create the rules.  Once again, place the following in the code-behind:

Listing 3

private int _MaxUserImageSize = 524288;
private int _MaxUserImageWidth = 600;
private int _MaxUserImageHeight = 600;
private const string _ImageTypeInvalid =
"Images are restricted to GIF or JPG";
private const string _ImageSizeInvalid =
"Images are restricted to 512k";

Add a button to the web form to handle the processing and a label to display any error messages:

Listing 4

<asp:label id="lblWarnings"
runat="server" visible="False"></asp:label>
<asp:button id="btnUpload"
runat="server" text="Next"></asp:button>

The event click for the previously created button should look like this:

Listing 5

private void btnUpload_Click(object sender,
System.EventArgs e)
{
  HttpPostedFile objFile =
FileUpload.PostedFile;
  // return when image is not valid
  if (!IsImageValid(FileUpload.PostedFile))
  return;
  lblWarnings.Text = "";
}

 

What is happening in Listing 5 is I am setting the file to upload to an object named objFile.  Then I am calling a method named IsImageValid to validate the file that the user is uploading against the rules I define back in Listing 2.

Note: I did not define the image file extension that I am expecting, as I will later provide a method that will perform this validation for me.

Add the following code to the code-behind below the btnUpload_Click method:

Listing 6

private bool IsImageValid(HttpPostedFile objFile)
{
  ValidateFiles validateImage = new
ValidateFiles();
  if (!Get_IsImageValid(objFile, validateImage))
   return SetError(_ImageTypeInvalid);
  if (!Get_IsImageDimensionsValid(objFile,
validateImage))
   return SetError(_ImageInvalidDimensions);
  if (!Get_IsImageSizeValid(objFile,
validateImage))
   return SetError(_ImageSizeInvalid);
   return true;
}
 
private bool SetError(string msg)
{
  if (!lblWarnings.Visible)
  lblWarnings.Visible = true;
  lblWarnings.Text = msg;
  return false;
}
 
private bool Get_IsImageValid(HttpPostedFile
objFile, ValidateFiles validateImage)
{
  return
validateImage.ValidateFileIsImage(objFile.ContentType);
}
 
private bool
Get_IsImageDimensionsValid(HttpPostedFile objFile, ValidateFiles validateImage)
{
  return
validateImage.ValidateUserImageDimensions(objFile);
}
 
private bool Get_IsImageSizeValid(HttpPostedFile
objFile, ValidateFiles validateImage)
{
  return
validateImage.ValidateUserImageSize(_MaxUserImageSize, objFile.ContentLength);
}

Now that the web form is all wired up to handle image uploads and to perform validation, the last piece of the puzzle is the ValidateFiles class from Listing 6.  Create a new class in the same location as the web form and name it ValidateFiles.cs.  Next simply cut and paste the following code:

Listing 7

public class ValidateFiles
{
  private bool _IsImage = false;
  private bool _IsOfficeDocument = false;
  private bool _ValidFileSize = false;
  private bool _ValidImageDimension =
false;
  private string _FileType = string.Empty;
  private int _FileSize = 0;
  private int _MaxWidth = 600;
  private int _MaxHeight = 600;
 
  public bool IsImage
  {
   get
   {
    return _IsImage;
   }
   set
   {
    _IsImage = value;
   }
  }
 
  public bool ValidFileSize
  {
   get
   {
    return _ValidFileSize;
   }
   set
   {
    _ValidFileSize = value;
   }
  }
 
  public string FileType
  {
   get
   {
    return _FileType;
   }
   set
   {
    _FileType = value;
   }
  }
 
  public bool ValidImageDimension
  {
   get
   {
    return _ValidImageDimension;
   }
   set
   {
    _ValidImageDimension = value;
   }
  }
 
  public ValidateFiles()
  {
   // Default construcor
  }
 
  public bool ValidateFileIsImage(string
fileType)
  {
   this._FileType = fileType;
   switch (fileType)
   {
     case "image/gif":
     case "image/jpeg":
     case
"image/pjpeg":
     IsImage = true;
     break;
     default:
     IsImage = false;
     break;
    }
     return IsImage;
   }
  
  public bool ValidateUserImageSize(int
maxFileSize, int fileSize)
  {
   this._FileSize = fileSize;
    if (maxFileSize > fileSize)
    return ValidFileSize = false;
    return ValidFileSize;
  }
 
  public bool
ValidateUserImageDimensions(HttpPostedFile file)
  {
   using (Bitmap bitmap = new
Bitmap(file.InputStream, false))
   {
    if (bitmap.Width < _MaxWidth
&& bitmap.Height < _MaxHeight)
    _ValidImageDimension = true;
    return ValidImageDimension;
   }
  }
 }
}

If you recall earlier, I stated there would be a method to provide validation for checking the image type.  In Listing 7, take a look at the ValidateFileIsImage method; to allow other types of images, simply add or remove fileTypes to meet your requirements.

Downloads

[Download Sample]

Conclusion

That is all there is to it.  By using this code snippet out of the box, you can limit image uploads to an image type of GIF or JPG, 512K in size, and 600x600 in resolution.

Feel free to discuss this code snippet at my blog.



©Copyright 1998-2024 ASPAlliance.com  |  Page Processed at 2024-04-18 6:49:40 PM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search