解决“超出最大请求长度”和FileUpload单个上载

时间:2013-02-20 22:38:54

标签: c# asp.net file-upload iis-7.5

我基本上有一个ASP.NET FileUpload控件,我需要为其提供以下消息抛出的异常:

  

超出最大请求长度。

限制是我需要限制用户上传一个文件,因为我已将其他详细信息从一些文本框保存到数据库中。

最大文件大小设置在web.config中设置如下:

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

因此我搜索了许多解决方案,如下所示:

  1. 在“Application_BeginRequest()”中使用Global.asax验证文件大小,但它没有解决我的问题,当文件大小较大且重定向到错误页面不起作用时,它在重定向时崩溃。

  2. 使用AjaxFileUpload而不是ASP.NET FileUpload控件,这在文件大小检查时再次崩溃,大于Web.config中允许的最大大小。 其次我必须限制总共用户只能上传一个文件,而不是一个文件,所以使用AjaxFileUpload它不能正常工作,因为我必须上传一个文件并将其他细节保存在某些文件中与该文件相关的文本框。 第三,当文件大小超过限制(即40MB)时,AjaxFileUpload只会变为红色,不会显示任何消息。

  3. 我想知道如何才能达到我的要求,因为我几天后就被困住了。

    更新:发现其中很少有用,但无法满足要求:

    以下是标记:

    <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" />
    

    以下是C#代码:

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

    除此之外,我已经找到了下面提到的解决方案。

    我使用了以下代码,虽然它现在正在运行Application_Error()代码部分,但问题是它没有重定向到About.aspx页面。

    我尝试重定向到Hotmail.com,但这也没有用,并且没有抛出任何异常。

    请找到以下代码部分:

    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)
        {
        }
    }
    

1 个答案:

答案 0 :(得分:21)

在Web配置文件中尝试以下设置。

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

httpRuntime - HTTP运行时设置。

executionTimeout - 没有。几秒钟的时间。

maxRequestLength - 文件的最大上传大小

有关详情,请点击link