Friday, June 13, 2008

Limiting File Upload Sizes with ASP.NET

Introduction
User can upload images of any arbitrary size. This is not good for either network traffic or database size, and raises the possibility of a nasty denial of service attack. So, the next step is to limit the uploaded file size to a reasonable value. The customer chose 128K as their maximum image size.
Your first thought might be to check the ContentLength property of the uploaded file to see if it's within the expected size, and to bail out of the procedure if it's too large. Unfortunately, this is only half of a solution. While that check would prevent the file from getting to the SQL Server database, it still requires the entire file to be uploaded first, potentially clogging the network. Fortunately, ASP.NET provides a better solution
It turns out that you can add a tag to the Web.Config file to specify a maximum size for uploaded files.

The maxRequestLength attribute of the httpRuntime tag specifies, in KB, the largest HTTP request that the application will accept. The default is 4096 KB, which is a little large for most applications. Be careful about setting this too low, though, as it applies to every request, not just uploaded files. If you're moving a lot of data around in ViewState, for example, you could run afoul of a too-low setting.
With this change to the Web.Config file, large files won't even be accepted by the server. But the user experience could use some work. What happens if the user tries to upload a large image with this setting in place:
"PAGE CANNOT BE DISPLAYED ERROR MESSAGE"
ASP.NET rejects the request in the rudest way possible, telling the client that there's no such page.
Telling the User What Happened
To get a better error message across to the user, you need to turn to another corner of the application. If your first impulse is to put a Try/Catch block in the page load to catch the error, think again: ASP.NET doesn't load the page at all in this situation. You have to move up the processing chain to the error event in the global.asax.vb file, which is called for every error in the application.
The strategy I settled on was to catch the error, and then redirect the user back to the original page with an error message. That way, they'll get a chance to try again with a different file. To start the process, I added some code to the global.asax.vb file:

Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
' Fires when an error occurs
' Check to see whether we came
' from the upload form
If Path.GetFileName(Request.Path) = "UploadForm.aspx" Then
' Get the error details
Dim appException As System.Exception = Server.GetLastError()
Dim checkException As HttpException = CType(appException, HttpException)
' Verify the expected error
If checkException.GetHttpCode = 400 And checkException.ErrorCode = -2147467259
Then
' Error 400 = bad request, user
' tried to upload a file that's too large
Session("ImageTooLarge") = True
Server.ClearError()
' Go to the original target page
Response.Redirect("UploadForm.aspx")
End If
End If
' For other errors, just accept the default processing
End Sub

The next step was to add a label control to the original upload form. The control's name is lblTooLarge, its text is a warning that the image is too large, and its Visible property is set to False. Then I modified the Page_Load procedure of the upload form:
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
If Not IsPostBack Then
' Check to see whether we were redirected
' from the error page
If Session("ImageTooLarge") = True Then
lblTooLarge.Visible = True
Exit Sub
End If
Else
' Get the uploaded data
Dim upfile As HttpPostedFile = UploadFile.PostedFile
' Remaining code unchanged ...
End If
End Sub

If the user tries to upload a file, the error gets caught in the global.asax file. At that point, the code retrieves the error details and verifies that this is the error that happened; I don't assume that it's the only possible error in the application! If it is, the code sets a flag in the session state and hands control back to the upload form. The upload form checks for the flag and makes the label visible so that the user will know what they did wrong.


3 comments:

Jerry said...

Hi Suomen,

This article is very useful, but I still have a problem. For some reason when a user uploads (lets say a 10MB file) I get the "PAGE CANNOT BE DISPLAYED ERROR MESSAGE". So what I did was go into my global.aspx.cs (I'm using C#) and only put Respond.Redirect("page1.aspx") in the Application_Error function. But even though I did that, I still only get "PAGE CANNOT BE DISPLAYED ERROR MESSAGE" when someone tries to upload a file. Why does it not send the user to page1.aspx? If you could let me know, I would really appreacite it.

HallsVaporAction said...

Suomen,

No offense, but did you even test your alleged solution?

Jerry, try the link below, look at the last solution presented:

http://nishantrana.wordpress.com/2009/01/19/fileupload-page-cannot-be-displayed-and-maximum-request-length-exceeded-error/

Soumen said...

Hi Halls,

I sincerely worked on this and after that only I provided the solution.


Regards,
Soumen