Friday, May 20, 2011

The Other Side of FileUpload Control.

1. The maximum size of the fileupload control 2GB for .net 2.0 and 1GB for .net 1.0.

2  The default maximum size of the fileupload control is 4MB.

3. How to do error handling if the file size exceeds 10 MB or N MB. The steps are as follows

3.1 Create the Global.asax file which should be in the root directory of your application.

3.2 Place the below code in the Application_AuthenticateRequest event
 
(HttpRuntimeSection)WebConfigurationManager.GetSection("system.web/httpRuntime");//Approx 100 Kb(for page content) size has been deducted because the maxRequestLength proprty is the page size, not only the file upload size
int maxRequestLength = (runTime.MaxRequestLength - 100) * 1024;//This code is used to check the request length of the page and if the request length is greater than //MaxRequestLength then retrun to the same page with extra query string value action=exception

{


(HttpWorkerRequest)provider.GetService(typeof(HttpWorkerRequest));// Check if body contains data
{
if (workerRequest.HasEntityBody())// get the total body length
int requestLength = workerRequest.GetTotalEntityBodyLength();// Get the initial bytes loaded

initialBytes

{
int initialBytes = 0;if (workerRequest.GetPreloadedEntityBody() != null)= workerRequest.GetPreloadedEntityBody().Length;if (!workerRequest.IsEntireEntityBodyIsPreloaded())byte[] buffer = new byte[512000];// Set the received bytes to initial bytes before start reading

{
int receivedBytes = initialBytes;while (requestLength - receivedBytes >= initialBytes)// Read another set of bytesinitialBytes = workerRequest.ReadEntityBody(buffer, buffer.Length);// Update the received bytesreceivedBytes
}

}
}
}

3.3  In the Application_Error add the following code

HttpContext context = HttpContext.Current;
Exception ex = Context.Server.GetLastError();
if(ex != null)
if (ex.InnerException.Message.ToString().ToLower().IndexOf("request length exceed") >= 0)
{
context.Server.ClearError();
context.Response.Redirect(Resources.Redirection.FileMaximumUploadError);
}

3.4. In the web.config add the following

<httpRuntime requestValidationMode="2.0" maxRequestLength="10240" executionTimeout="600" />

maxRequestLength in kilobytes =eg. 10 Mb

3.5. In the FileMaximumUploadError.aspx add the error Message.

No comments:

Post a Comment