I’m trying to limit the file upload size of a site to 2 MB. For this, I tried two methods, both of which failed.
In the first method, I set the maxRequestLength attribute of the httpRuntime element in the web.config file to 2048 KB. During the upload in the corresponding page, I check the size of the uploading file and allow upload if it’s within the permissible limit.
Example:
<configuration>
<system.web>
<compilation debug="true" strict="false" explicit="true" targetFramework="4.0" />
<pages styleSheetTheme="Default"></pages>
<httpRuntime maxRequestLength = "2048" />
</system.web>
<connectionStrings>
<add name="TestConnection" connectionString="Data Source=localhost;Initial Catalog=TestDB;User ID=sa;password=" />
</connectionStrings>
</configuration>
In the code editor of the page:
If ImageUpload.PostedFile.ContentLength <= 2097152 Then
End If
If the file size is within 2 MB then everything goes fine. As soon as the file size exceeds the limit, it crashes. As a workaround, I increased maxRequestLength in web.config to a much higher value- 35840 KB (35 MB) while keeping the validation method in the page intact. This time, any file with actual memory of 35 MB or less is validated properly with a constraint of 2 MB by the page method. But as soon the actual memory of the file exceeds 35 MB the site crashes again.
In the second method, I added a Global.asax file to the site. In its Application_Error method I check if the exception is raised due to exceeding of the maximum request length. If yes, then it should redirect to the same page from which the exception is raised with an error message in the query string. When the page re-loads it should show the error message.
But during runtime, though the Application_Error method is getting executed, it crashes again.
Global.asax example:
Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
If HttpContext.Current.Request.Url.ToString.Contains("Customer.aspx") Then
If HttpContext.Current.Error.InnerException.Message.Contains("Maximum request length exceeded") Then
HttpContext.Current.ClearError()
HttpContext.Current.Response.Redirect(String.Format("~/Customer.aspx?ErrorMessage={0}", "The file cannot be uploaded because it exceeds the 2 MB size limit."))
End If
End If
End Sub
Please help to sort out this problem. Regards.