Quantcast
Channel: Web Forms
Viewing all articles
Browse latest Browse all 23244

Resolve "Maximum request length exceeded" and FileUpload single upload.

$
0
0

I am using Visual Studio 2010/ASP.NET/C-Sharp website.

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>

And
<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.
Kindly help me in this regards as early as possible.

Found few of them useful, but could not accomplish the requirements on their basis:-
http://stackoverflow.com/questions/2759193/display-custom-error-page-when-file-upload-exceeds-allowed-size-in-asp-net-mvc
http://stackoverflow.com/questions/3853767/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 the ASPX Code:-

    <asp:Label ID="lblStatus" runat="server" Text=""></asp:Label>
    <br/><br/>
    <asp:FileUpload ID="theFile" runat="server" />
    <asp:Button ID="Button2" runat="server" Text="Upload 1"
        onclick="Button2_Click" />

    <br/><br/>

    <asp:Button ID="Button1" runat="server" Text="Upload 1"
        onclick="btnUpload1_Click" />
        <br/><br/>
    <asp:Button ID="btnUpload" runat="server" Text="btnUpload_Click"
        onclick="btnUpload_Click" />
        
          <br/><br/>
          
          <asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>
    <br /><br />
     <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"/>
     <br /><br />
       <asp:Image id="MyThrobber" ImageUrl="~/UploadedFiles/Penguins.jpg" AlternateText="Saving...."  Style="display:None"  Height="1px" Width="350px" runat="server" />

Following is the C-Sharp 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)
    {
        #region Attachments File & Log Addition Section
        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.";
                    }
                }

            }// End- if(filename=="")

          



        }
        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();
        }
        #endregion
    }

    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");
        }

    }


Viewing all articles
Browse latest Browse all 23244

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>