Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resolve "Maximum request length exceeded" and FileUpload single upload

I basically had an ASP.NET FileUpload control, for which I needed to cater the exception thrown for the following message:

Maximum request length exceeded.

The limitations are that I need to just restrict the user to upload one file in all because I have save the other details from some text-boxes into DB.

The maximum file size setting is set in the web.config as follows:

<system.webServer>
    <security>
        <requestFiltering>
            <requestLimits maxAllowedContentLength="41943040" />
        </requestFiltering>
    </security>
</system.webServer>
<system.web>
    <httpRuntime maxRequestLength="40960" requestValidationMode="2.0" />
</system.web>

So therefore I searched many solutions, to name then as follows:

  1. Usage Global.asax with validating file size in "Application_BeginRequest()", but it has not resolved my issue and it crashes at the Redirect when file size is greater and a redirect to Error Page is not working.

  2. Usage of AjaxFileUpload instead of ASP.NET FileUpload control, this is again crashes at the checking of file size is greater than maximum size allowed in Web.config. Secondly I have to restrict that in total the user can just upload one single file, not more than one file, so using the AjaxFileUpload it is not working in my condition, since I have to upload a single document and save the other details in some text-boxes related to that file. Thirdly when the file size exceeds the limit, i.e. 40MB, then the AjaxFileUpload just gets red colour, no message is shown.

I want to find out that how can I accomplish my requirements, since I am stuck for this since a couple of days.

Update: Found few of them useful, but could not accomplish the requirements on their basis:

  • Display custom error page when file upload exceeds allowed size in ASP.NET MVC
  • Maximum request length exceeded
  • http://dotnetslackers.com/Community/blogs/haissam/archive/2008/09/12/upload-large-files-in-asp-net-using-httpmodule.aspx
  • http://geekswithblogs.net/sglima/archive/2011/09/20/how-to-handle-maximum-request-length-exceeded-exception.aspx
  • http://dotnetpools.com/Article/ArticleDetiail/?articleId=52&title=Ajax%20AsyncFileUpload%20Example%20In%20Asp.net%20To%20Upload%20Files%20To%20Server%20Using%20AjaxFileUpload%20Control

Following is markup:

<asp:Label ID="lblStatus" runat="server" Text=""></asp:Label>
<asp:FileUpload ID="theFile" runat="server" />
<asp:Button ID="Button2" runat="server" Text="Upload 1"  onclick="Button2_Click" />
<asp:Button ID="Button1" runat="server" Text="Upload 1"  onclick="btnUpload1_Click" />
<asp:Button ID="btnUpload" runat="server" Text="btnUpload_Click" onclick="btnUpload_Click" />
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<asp:AjaxFileUpload ID="AjaxFileUpload2" runat="server" ToolTip="Upload File" ThrobberID="MyThrobber" onclientuploaderror="IsFileSizeGreaterThanMax" onuploadcomplete="AjaxFileUpload1_UploadComplete" AllowedFileTypes="jpg,jpeg,gif,png,pjpeg,zip,rar,pdf,xls,xlsx,doc,docx" MaximumNumberOfFiles="1" Height="50px" Width="350px"/>
<asp:Image id="MyThrobber" ImageUrl="~/UploadedFiles/Penguins.jpg" AlternateText="Saving...."  Style="display:None"  Height="1px" Width="350px" runat="server" />

Following is C# code:

protected void Button2_Click(object sender, EventArgs e)
{
    if (theFile.HasFile)
    {
         HttpRuntimeSection runTime = (HttpRuntimeSection)System.Configuration.ConfigurationManager.GetSection("system.web/httpRuntime");
        double maxRequestLength = (runTime.MaxRequestLength - 100) * 1024;
        double xxx = theFile.PostedFile.ContentLength;
        double ck = xxx / 1024 / 1024;
        bool f = false;
        if (ck > maxRequestLength)
        {
            f = true;
        }
        lblStatus.Text = xxx.ToString() + " " + (f ? "too big" : "size ok");
    }
 }

protected void btnUpload1_Click(object sender, EventArgs e)
{
     try
     {

        if ((theFile.PostedFile != null) && (theFile.PostedFile.FileName != ""))
         {
             if ((theFile.PostedFile != null) && (theFile.PostedFile.FileName != ""))
             {
                 fileName = theFile.PostedFile.FileName;
                 Session["FileAttached"] = fileName;
             }
             else
             {
                 Session["FileAttached"] = "";
                 lblStatus.Focus();
                 lblStatus.ForeColor = System.Drawing.Color.Red;
                 lblStatus.Text += "<br/>Attachment file not found.";
                 return;
             }
             if (fileName != "")
             {
                 cFilePath = Path.GetFileName(fileName);

                /*UpPath = "../UploadedFiles";
                 fullPath = Server.MapPath(UpPath);
                 fileNpath = fullPath + "\\" + cFilePath;*/

                if (theFile.HasFile)
                 {
                     string CompletePath = "D:\\Visual Studio 2010\\DevLearnings\\FileAttachSizeMax\\UploadedFiles\\";
                     if (theFile.PostedFile.ContentLength > 10485760)
                     {
                         lblStatus.Focus();
                         lblStatus.ForeColor = System.Drawing.Color.Red;
                         lblStatus.Text += "File size is greater than the maximum limit.";
                     }
                     else
                     {
                         theFile.SaveAs(@CompletePath + theFile.FileName);
                         lblStatus.Text = "File Uploaded: " + theFile.FileName;
                     }
                 }
                 else
                 {
                     lblStatus.Text = "No File Uploaded.";
                 }
             }
        }
     }
     catch (Exception ex)
     {
         lblStatus.Focus();
         lblStatus.ForeColor = System.Drawing.Color.Red;
         lblStatus.Text += "Error occurred while saving Attachment.<br/><b>Error:</b> " + ex.Source.ToString() + "<br/><b>Code:</b>" + ex.Message.ToString();
     }
 }

protected void AjaxFileUpload1_UploadComplete(object sender, AjaxControlToolkit.AjaxFileUploadEventArgs e)
{
    HttpRuntimeSection runTime = (HttpRuntimeSection)System.Configuration.ConfigurationManager.GetSection("system.web/httpRuntime");
    int maxRequestLength = (runTime.MaxRequestLength - 100) * 1024;

    if (e.FileSize <= maxRequestLength)
    {
         string path = MapPath("~/UploadedFiles/");
         string fileName = e.FileName;
         AjaxFileUpload2.SaveAs(path + fileName);
     }
     else
     {
         lblStatus.Text = "File size exceeds the maximum limit. Please use file size not greater than 40MB. ";
         return;
     }
}

protected void btnUpload_Click(object sender, EventArgs e)
{
     //AsyncFileUpload.SaveAs();
     //AjaxFileUpload1.SaveAs();

    HttpContext context = ((HttpApplication)sender).Context;
     //HttpContext context2 = ((System.Web.UI.WebControls.Button)sender).Context;

    HttpRuntimeSection runTime = (HttpRuntimeSection)System.Configuration.ConfigurationManager.GetSection("system.web/httpRuntime");
    double maxRequestLength = (runTime.MaxRequestLength - 100) * 1024;

    if (context.Request.ContentLength > maxRequestLength)
    {
         IServiceProvider provider = (IServiceProvider)context;
         HttpWorkerRequest wr = (HttpWorkerRequest)provider.GetService(typeof(HttpWorkerRequest));
         FileStream fs = null;
         // Check if body contains data
         if (wr.HasEntityBody())
         {
             // get the total body length
             int requestLength = wr.GetTotalEntityBodyLength();
             // Get the initial bytes loaded
             int initialBytes = wr.GetPreloadedEntityBody().Length;

            if (!wr.IsEntireEntityBodyIsPreloaded())
            {
                 byte[] buffer = new byte[512000];
                 string[] fileName = context.Request.QueryString["fileName"].Split(new char[] { '\\' });
                 fs = new FileStream(context.Server.MapPath("~/UploadedFiles/" + fileName[fileName.Length - 1]), FileMode.CreateNew);
                 // Set the received bytes to initial bytes before start reading
                 int receivedBytes = initialBytes;
                 while (requestLength - receivedBytes >= initialBytes)
                 {
                     // Read another set of bytes
                     initialBytes = wr.ReadEntityBody(buffer, buffer.Length);
                     // Write the chunks to the physical file
                     fs.Write(buffer, 0, buffer.Length);
                     // Update the received bytes
                     receivedBytes += initialBytes;
                 }
                 initialBytes = wr.ReadEntityBody(buffer, requestLength - receivedBytes);
            }
         }
         fs.Flush();
         fs.Close();
         context.Response.Redirect("About.aspx");
     }
}

Apart from the above, I have come to a solution mentioned below.

I have used the following code, although it is now running the Application_Error() Code section, but the problem is that it is not redirecting to the About.aspx page.

I tried to redirect to Hotmail.com, but that too did not work, and no exception is thrown.

Please find the below code section:

private void Application_Error(object sender, EventArgs e) 
{ 
    // Code that runs when an unhandled error occurs
    Exception exc = Server.GetLastError();
    try
    {
        if (exc.Message.Contains("Maximum request length exceeded"))
        {
            //Response.Redirect("~/About.aspx", false);
            Response.Redirect("http://www.example.com", false);
        }
        if (exc.InnerException.Message.Contains("Maximum request length exceeded"))
        {
            Response.Redirect("http://www.HOTMAIL.com", false);
        }
    }
    catch (Exception ex)
    {
    }
}
like image 410
Muzaffar Ali Rana Avatar asked Nov 28 '22 16:11

Muzaffar Ali Rana


1 Answers

Try the following setting in the web config file.

<system.web>
<httpRuntime executionTimeout="9999" maxRequestLength="2097151"/>
</system.web>

httpRuntime - HTTP runtime settings.

executionTimeout - no. of seconds to time out.

maxRequestLength - maximum upload size of the file

For more details click the link

like image 74
Arun Kumar T Avatar answered Dec 01 '22 05:12

Arun Kumar T