Check for file type and image size before uploading a file
In my applications, the functionality allowing end users to upload various types of files to the web server or even into a database is a given. The need to to check and constrain the file type and file size before allowing it to be saved on your server space is also obvious. It wouldn't be wise to unnecessarily let users upload 50MB+ files to your web server over and over.
In one instance, I wanted to let authenticated users upload logo files into a BLOB field in a production database. Since the file to be uploaded is intended to be a small image used as personalization on customer account pages, as well as the fact that the file was being saved in a database table in a binary field, I check for and only allow certain image types (.jpg, .gif, .png, .bmp) and constrain the maximum image size to 150 pixels by 150 pixels. Enforcing the maximum pixel restrictions alone will keep most files below the 5 kb range, but I still check for file size as well.
The code below utilizes an upload input control on the UI side that runs my method to 1. check file type, 2. check file size (content length), and 3. if the file type is a predefined image type, check the size of the image to make sure that it is no greater than 1200 pixels by 1200 pixels.
ASPX Markup
I'm using an .NET upload control called UploadDocument. This control allows the user to browse their hard disk for a file to upload. The button btnUpload is hooked to an onclick event called UploadDoc, which will run the method that checks the file type and size and will determine to accept the upload or not. The upload success message will be displayed in the label control called lblUploadMessage.
<div class="CodeCon" style="padding-left:16px;">
<asp:Label runat="server" ID="lblUploadMessage" Text="Select a document to upload:" Font-Bold="true" />
<br />
<div style="padding-top: 8px; padding-left: 12px;">
<asp:FileUpload ID="UploadDocument" runat="server" Width="340px" />
<br />
<br />
<asp:Button runat="server" ID="btnUpload" CssClass="Button" Text="Upload Document" Enabled="false" />
</div>
The resulting UI looks like this.
Now let's take a look at the event UploadDoc.
C#
protected void UploadDoc(object sender, EventArgs e)
{
try
{
//Make sure a file has been successfully uploaded
if (uploadDocument.PostedFile == null || string.IsNullOrEmpty(uploadDocument.PostedFile.FileName) || uploadDocument.PostedFile.InputStream == null) {
// Error occurred on upload
lblUploadMessage.Text = "An error occurred while uploading the file. Please try again.";
}
HttpPostedFile file = uploadDocument.PostedFile;
// Get the extension of the file to check file type
string extension = Path.GetExtension(file.FileName).ToLower();
switch (extension){
case ".gif":
case ".jpg":
case ".jpeg":
case ".jpg":
case ".png":
// Check pixel height and width to make sure it conforms to our predefined dimensions
//Create an instance of an image from the posted file
Image img = System.Drawing.Image.FromStream(uploadDocument.PostedFile.InputStream);
// Get the new image's dimensions
Single imgHeight = img.PhysicalDimension.Height;
Single imgWidth = img.PhysicalDimension.Width;
if (imgHeight > 1200 | imgWidth > 1200) {
lblUploadMessage.Text = "This image is too large. The maximum image height is 1200 pixels and the maximum image width is 1200 pixels.";
}
break;
case ".xls":
case ".doc":
case ".rtf":
case ".pdf":
case ".txt":
// Other document, can perform more validation if necessary
break;
default:
//Invalid file type uploaded
lblUploadMessage.Text == "The file type is invalid. Acceptable document types include Adobe Acrobat .pdf, " + "Microsoft Word (.doc, .rtf), and Microsoft Excel .xls.<br/><br/>" + "Acceptable image types include .jpg, .gif, .png, .tif files."
}
// Check to make sure file size is less than 1 million bytes (1 mb)
{
if (file.ContentLength < 1000000 == true) {
// Save the file on disk
// Use Server.MapPath to find your directory to save the file
file.SaveAs(Server.MapPath("YourDirectory/") + fileName + ext);
}
else {
lblUploadMessage.Text = "The file to upload is exceeds 1 megabyte in size.";
}
}
}
catch (Exception)
{
EmailError.emailHandledError(ex);
lblUploadMessage.Text = "An error has occurred. The site administrator has been " + "notified of this error.";
}
}
}
VB.NET:
Imports System.Drawing
Imports System.IO
Protected Sub UploadDoc(ByVal sender As Object, ByVal e As System.EventArgs)
' Check file information
Try
'Make sure a file has been successfully uploaded
If uploadDocument.PostedFile Is Nothing _
OrElse String.IsNullOrEmpty(uploadDocument.PostedFile.FileName) _
OrElse uploadDocument.PostedFile.InputStream Is Nothing Then
' Error occurred on upload
lblUploadMessage.Text = "An error occurred while uploading the file. Please try again."
End If
Dim file As HttpPostedFile = uploadDocument.PostedFile
' Get the extension of the file to check file type
Dim extension As String = Path.GetExtension(file.FileName).ToLower()
Select Case extension
Case ".gif", ".jpg", ".jpeg", ".jpe", ".png"
' Check pixel height and width to make sure it conforms to our predefined dimensions
' Create an instance of an image from the posted file
Dim img As Image = Image.FromStream(uploadDocument.PostedFile.InputStream)
' Get the new images dimensions
Dim imgHeight As Single = img.PhysicalDimension.Height
Dim imgWidth As Single = img.PhysicalDimension.Width
If imgHeight > 1200 Or imgWidth > 1200 Then
lblUploadMessage.Text "This image is too large. The maximum image height is 1200 pixels" _
& " and the maximum image width is 1200 pixels."
End If
Case ".xls", ".doc", ".rtf", ".pdf", ".txt"
' Other document, can perform more validation if necessary
Case Else
'Invalid file type uploaded
lblUploadMessage.Text = "The file type is invalid. Acceptable document types include Adobe Acrobat .pdf, " _
& "Microsoft Word (.doc, .rtf), and Microsoft Excel .xls.<br/><br/>" _
& "Acceptable image types include .jpg, .gif, .png, .tif files."
End Select
' Check to make sure file size is less than 1 million bytes (1 mb)
If file.ContentLength < 1000000 = True Then
' Save the file on disk
' Use Server.MapPath to find your directory to save the file
file.SaveAs(Server.MapPath("YourDirectory/") & fileName & ext)
Else
lblUploadMessage.Text = "The file to upload is exceeds 1 megabyte in size."
End If
Catch ex As Exception
EmailError.emailHandledError(ex)
lblUploadMessage.Text = "An error has occurred. The site administrator has been " _
& "notified of this error."
End Try
End Sub
In the code, the first condition to check is to make sure a file was uploaded. If that condition is satisfied, we then declare UploadDocument.PostedFile with the alias file to make it easier to refer to. We then do the same thing with the file extension, assigning it to a string variable.
We then look through the acceptable file extensions using a Select Case/Switch statment. In this case, it's a lot prettier in VB.NET. If the file extension matches one of my pre-defined image types - ".gif", ".jpg", ".jpeg", ".jpe", ".png" - then I create an instance of ASP.NET's image class from the posted file's input stream and check the image height and image width.
If the file type doesn't match any of the other file types in the statement, we let the user know that the file type they uploaded is invalid and stop the upload.
Lastly, we check the content length (file size) of the file being uploaded. If the file fits within our pre-defined limitations, then we save the file using the file.SaveAs function, using the Server.MapPath function to find the specificed directory in which to save the file. Happy coding!