使用asp:FileUpLoad控件上传文件时文件太大

我正在使用asp:FileUpLoad上传我的asp.net c#项目中的文件。 只要文件大小不超过允许的最大值,这一切都可以正常工作。 超过最大值时。 我收到错误“ Internet Explorer cannot display the webpage ”。 问题是try catch块没有捕获错误,所以我不能给user a friendly message ,他们已经删除了允许的大小。 我在搜索网页时看到了这个问题,但我找不到可接受的解决方案。

我会看看其他控件,但我的管理可能不会购买第三方控件。

根据建议ajac的答案,我需要添加此评论。 几个月前我试图加载ajax控件。 一旦我使用ajax控件,我就会收到此编译错误。

错误98“System.Web.UI.ScriptControl”类型在未引用的程序集中定义。 您必须添加对程序集’System.Web.Extensions,Version = 4.0.0.0,Culture = neutral,PublicKeyToken = 31bf3856ad364e35’的引用。

虽然我添加了’ System.Web.Extensions ‘,但我可以摆脱它。 所以我放弃了Ajax并使用了其他技术。

所以我需要解决这个问题或一个全新的解决方案。

默认文件大小限制为(4MB),但您可以通过在上载页面所在的目录中删除web.config文件以本地化方式更改默认限制。 这样你就不必让你的整个网站允许大量上传(这样做会让你受到某种攻击)。

只需在部分下的web.config中进行设置即可。 例如,在下面的示例中,我将最大长度设置为2GB

  

请注意, maxRequestLength以KB为单位设置,最高可设置为2GB (2079152 KB's) 。 实际上我们通常不需要设置2GB请求长度,但如果将请求长度设置得更高,我们还需要增加executionTimeout

Execution Timeout Specifies the maximum number of seconds that a request is allowed to execute before being automatically shut down by ASP.NET. (Default time is 110 seconds.)

有关详细信息,请阅读httpRuntime元素(ASP.NET设置架构)

现在,如果要向用户显示自定义消息,如果文件大小大于100MB

你可以这样做..

 if (FileUpload1.HasFile && FileUpload1.PostedFile.ContentLength > 104857600) { //FileUpload1.PostedFile.ContentLength -- Return the size in bytes lblMsg.Text = "You can only upload file up to 100 MB."; } 
  1. 在客户端,Flash和/或ActiveX和/或Java和/或HTML5 Files API是测试文件大小和阻止提交的唯一方法。 使用像Uploadify这样的包装器/插件,您不必自己动手,就可以获得跨浏览器解决方案。

  2. 在服务器上,在global.asax ,输入:

     public const string MAXFILESIZEERR = "maxFileSizeErr"; public int MaxRequestLengthInMB { get { string key = "MaxRequestLengthInMB"; double maxRequestLengthInKB = 4096; /// This is IIS' default setting if (Application.AllKeys.Any(k => k == key) == false) { var section = ConfigurationManager.GetSection("system.web/httpRuntime") as HttpRuntimeSection; if (section != null) maxRequestLengthInKB = section.MaxRequestLength; Application.Lock(); Application.Add(key, maxRequestLengthInKB); Application.UnLock(); } else maxRequestLengthInKB = (double)Application[key]; return Convert.ToInt32(Math.Round(maxRequestLengthInKB / 1024)); } } void Application_BeginRequest(object sender, EventArgs e) { HandleMaxRequestExceeded(((HttpApplication)sender).Context); } void HandleMaxRequestExceeded(HttpContext context) { /// Skip non ASPX requests. if (context.Request.Path.ToLowerInvariant().IndexOf(".aspx") < 0 && !context.Request.Path.EndsWith("/")) return; /// Convert folder requests to default doc; /// otherwise, IIS7 chokes on the Server.Transfer. if (context.Request.Path.EndsWith("/")) context.RewritePath(Request.Path + "default.aspx"); /// Deduct 100 Kb for page content; MaxRequestLengthInMB includes /// page POST bytes, not just the file upload. int maxRequestLength = MaxRequestLengthInMB * 1024 * 1024 - (100 * 1024); if (context.Request.ContentLength > maxRequestLength) { /// Need to read all bytes from request, otherwise browser will think /// tcp error occurred and display "uh oh" screen. ReadRequestBody(context); /// Set flag so page can tailor response. context.Items.Add(MAXFILESIZEERR, true); /// Transfer to original page. /// If we don't Transfer (do nothing or Response.Redirect), request /// will still throw "Maximum request limit exceeded" exception. Server.Transfer(Request.Path); } } void ReadRequestBody(HttpContext context) { var provider = (IServiceProvider)context; var workerRequest = (HttpWorkerRequest)provider.GetService(typeof(HttpWorkerRequest)); // Check if body contains data if (workerRequest.HasEntityBody()) { // get the total body length int requestLength = workerRequest.GetTotalEntityBodyLength(); // Get the initial bytes loaded int initialBytes = 0; if (workerRequest.GetPreloadedEntityBody() != null) initialBytes = workerRequest.GetPreloadedEntityBody().Length; if (!workerRequest.IsEntireEntityBodyIsPreloaded()) { byte[] buffer = new byte[512000]; // Set the received bytes to initial bytes before start reading int receivedBytes = initialBytes; while (requestLength - receivedBytes >= initialBytes) { // Read another set of bytes initialBytes = workerRequest.ReadEntityBody(buffer, buffer.Length); // Update the received bytes receivedBytes += initialBytes; } initialBytes = workerRequest.ReadEntityBody(buffer, requestLength - receivedBytes); } } } 

    创建一个您的页面将inheritance的BasePage类,并将此代码添加到它:

     public int MaxRequestLengthInMB { get { return (Context.ApplicationInstance as Global).MaxRequestLengthInMB; } } protected override void OnInit(EventArgs e) { base.OnInit(e); CheckMaxFileSizeErr(); } private void CheckMaxFileSizeErr() { string key = Global.MAXFILESIZEERR; bool isMaxFileSizeErr = (bool)(Context.Items[key] ?? false); if (isMaxFileSizeErr) { string script = String.Format("alert('Max file size exceeded. Uploads are limited to approximately {0} MB.');", MaxRequestLengthInMB); ScriptManager.RegisterClientScriptBlock(this, this.GetType(), key, script, true); } } 

    最后,在web.config必须设置maxAllowedContentLength(以字节为单位)大于maxRequestLength(以kB为单位)。


   
 

 
   <安全>
     <的requestFiltering>
       
     
   
 

事实上,尝试捕获对你没有帮助。 但这是一个解决方法:您可以处理Global.asax Application_Error方法中的错误。

示例:

 void Application_Error(object sender, EventArgs e) { // manage the possible 'Maximum Length Exceeded' exception HttpContext context = ((HttpApplication)sender).Context; /* test the url so that only the upload page leads to my-upload-error-message.aspx in case of problem */ if (context.Request.Url.PathAndQuery.Contains("mypage")) Response.Redirect("/my-upload-error-message.aspx"); } 

当然,请注意,如果在“mypage”页面上发生任何其他类型的错误,您将被重定向到/my-upload-error-message.aspx,无论发生了什么。

您可以尝试使用asp.net工具包上传控件。 免费!

http://www.asp.net/ajax/ajaxcontroltoolkit/samples/AsyncFileUpload/AsyncFileUpload.aspx

这似乎是会话超时的问题,增加会话时间,然后再试一次。 您可以在web.config文件中设置会话时间

在您的web.config中,将允许的最大内容长度设置为高于您要接受的范围:

        

然后,在global.asax中,使用Application_BeginRequest设置自己的限制:

  private const int MyMaxContentLength = 10000; //Wathever you want to accept as max file. protected void Application_BeginRequest(object sender, EventArgs e) { if ( Request.HttpMethod == "POST" && Request.ContentLength > MyMaxContentLength) { Response.Redirect ("~/errorFileTooBig.aspx"); } }