C# 解决“最大请求长度超出”和 FileUpload 单次上传

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14991294/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 13:41:26  来源:igfitidea点击:

Resolve "Maximum request length exceeded" and FileUpload single upload

c#asp.netfile-uploadiis-7.5

提问by Muzaffar Ali Rana

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

我基本上有一个 ASP.NET FileUpload 控件,为此我需要处理为以下消息引发的异常:

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:

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

<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.

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

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

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:

更新:发现其中很少有用,但无法在其基础上完成要求:

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:

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

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.

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

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

我试图重定向到 Hotmail.com,但这也不起作用,也没有抛出异常。

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

回答by Arun Kumar T

Try the following setting in the web config file.

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

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

httpRuntime- HTTP runtime settings.

httpRuntime- HTTP 运行时设置。

executionTimeout- no. of seconds to time out.

executionTimeout- 没有。秒到超时。

maxRequestLength- maximum upload size of the file

maxRequestLength- 文件的最大上传大小

For more details click the link

更多详情请点击链接