c# - 解决 "Maximum request length exceeded"和FileUpload单次上传

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

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

Maximum request length exceeded.

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

最大文件大小设置在 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 只会变成红色,不会显示任何消息。

我想知道我怎样才能完成我的要求,因为几天以来我一直被困在这个问题上。

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

以下是标记:

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

最佳答案

尝试在网络配置文件中进行以下设置。

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

httpRuntime - HTTP 运行时设置。

executionTimeout - 没有。超时秒数。

ma​​xRequestLength - 文件的最大上传大小

有关详细信息,请单击 link

关于c# - 解决 "Maximum request length exceeded"和FileUpload单次上传,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14991294/

相关文章:

c# - 如何阻止自定义 ThrowHelper 出现在您的 StackTrace 中?

c# - 动态参数的问题

c# - asp.net core 2.0身份 Entity Framework 用户未保存

c# - StringBuilder.Append with float

javascript - Express js 中的文件上传再次出现问题

c# - 如何在代码隐藏中创建 ResourceDictionary?

c# - 从专有名称中提取通用名称

ASP.NET MVC3 文件上传不工作

java - 使用 multipart 发送附加数据

javascript - 基于浏览器的本地文件系统到 SVG base64 数据字符串