4

我基本上有一个 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. 使用 Global.asax 在“Application_BeginRequest()”中验证文件大小,但它没有解决我的问题,当文件大小更大并且重定向到错误页面不起作用时,它在重定向时崩溃。

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

1 回答 1

24

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

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

httpRuntime - HTTP 运行时设置。

executionTimeout - 没有。秒超时。

maxRequestLength - 文件的最大上传大小

更多详情请点击链接

于 2014-08-24T05:55:20.280 回答