ASP.Net文件上传研究之二——一种更高效的限制上传文件大小的方法

来源:互联网 发布:中英文翻译软件下载 编辑:程序博客网 时间:2024/06/15 22:37

     上一篇中我们讨论了ASP.Net文件上传的方法,但是这种方法还不够完善,当Form表单提交的数据超过maxRequestLength(.Net默认为4M)时就会出现“The page cannot be displayed”的错误页面,而且这个页面非常的不友好,普通用户可能会认为是系统出了什么故障,根本无从知晓是因为自己上传的文件超过了规定的要求,所以必须得想办法解决这个问题。

     大家都知道通过增大Web.config文件里maxRequestLength的值可以改变.Net默认4M的限制,让我们可以提交更大的Form表单,也就意味着可以上传更大的文件,这个maxRequestLength最大可以设置为2197151,也就是说理论上能提交的Form表单的最大数据量为2197151KB,约为2.095GB,如果忽略表单中的其他表单项,那就可以上传2GB的文件(以95M的零头来存放除File以外的其他表单项问题应该不大吧!),但是请注意,在改变maxRequestLength解决“The page cannot be displayed”错误的同时在Form表单里的其他表单项数据固定的情况下,用户能上传的文件也在变大,但是在很多时候我们并不希望用户上传太大的文件,如果把maxRequestLength设小,出现“The page cannot be displayed”的几率又会增大,那么究竟要如何限制用户上传文件的大小同时不出现“The page cannot be displayed”错误呢?

    一般的做法是通过HttpRequest对象的ContentLength属性来取得Form表单提交的数据的大小,然后判断是否超过了限额,如果超过限额就给出一个出错提示,或者是通过HttpRequest对象的Files属性取得Form表单提交的所有文件,然后遍历这些文件通过ContentLength取得每个文件的大小,如果有文件超过了限额就给出一个出错提示。这两种方法都可以,但是这两种方法都比较占用服务器的资源,原因是在使用HttpRequest对象时Form表单里的所有数据都已经缓存到服务器上了,甚至都写到服务器的磁盘上了,(按照微软的说法,默认情况下Form表单提交的的数据超过256KB就会被缓存到磁盘上,原文如下:“Files are uploaded in MIME multipart/form-data format. By default, all requests, including form fields and uploaded files, larger than 256 KB are buffered to disk, rather than held in server memory”,详见:http://msdn.microsoft.com/en-us/library/system.web.httppostedfile.aspx

    另一个办法就是在HttpHandler处理Request之前先判断Form表单的数据是否超过了限额,如果超过了限额那就忽略Form表单提交的数据,直接返回出错提示。具体代码如下:

 

1、修改web.config文件,在appsetting增加以下内容:

  1. <!--自定义Form表单大小限制 单位:KB(10240表示10M )-->
  2. <add key="customMaxRequestLength" value="10240"/>  

 2、修改web.config文件,在system.web中修改一下内容:(没有就添加)

  1. <httpRuntime maxRequestLength="2097151"
  2.     useFullyQualifiedRedirectUrl="true"
  3.          executionTimeout="6000"
  4.         minFreeThreads="8"
  5.         minLocalRequestFreeThreads="4"
  6.             appRequestQueueLimit="100"
  7.             enableVersionHeader="true"
  8. />

3、在网站根目录下增加Global.asax文件

  1. <%@ Application Language="VB" %>
  2. <script runat="server">
  3.     
  4.     Protected Sub Application_BeginRequest(ByVal sender As ObjectByVal e As System.EventArgs)        
  5.         
  6.         Dim application As HttpApplication = CType(sender, HttpApplication)
  7.         Dim context As HttpContext = application.Context
  8.         Dim wr As HttpWorkerRequest = GetWorkerRequest()
  9.         
  10.         Dim mybindingflags As System.Reflection.BindingFlags = Reflection.BindingFlags.Instance Or Reflection.BindingFlags.NonPublic
  11.         '取content_type
  12.         Dim content_type As String = application.Request.ContentType
  13.         '只处理enctype为"multipart/form-data" 的Form提交的请求
  14.         If (Not content_type.ToLower().StartsWith("multipart/form-data")) Then Return
  15.         '只处理包含body数据的Request
  16.         If (Not wr.HasEntityBody()) Then Return
  17.         
  18.         '取Request的总长度
  19.         Dim contentlen As Int32 = wr.GetTotalEntityBodyLength()
  20.         If contentlen < (System.Configuration.ConfigurationManager.AppSettings("customMaxRequestLength") * 1024) Then Return
  21.                 
  22.         Dim hct As Type = wr.GetType
  23.         
  24.         hct.GetMethod("SkipAllPostedContent", mybindingflags).Invoke(wr, Nothing)
  25.         hct.GetField("_preloadedContent", mybindingflags).SetValue(wr, Nothing)
  26.         hct.GetField("_contentLength", mybindingflags).SetValue(wr, 0)
  27.                 
  28.         context.Response.Redirect("~/uploaderror.aspx")
  29.     End Sub
  30.     
  31.     Private Function GetWorkerRequest() As HttpWorkerRequest
  32.         Dim provider As IServiceProvider = HttpContext.Current
  33.         Return CType(provider.GetService(GetType(HttpWorkerRequest)), HttpWorkerRequest)
  34.     End Function
  35. </script>

4、index.aspx文件,用来提交表单

  1. <html> 
  2. <head> 
  3. <meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> 
  4. <title>无标题文档</title> 
  5. </head> 
  6. <body> 
  7. <form action="save.aspx" method="post" enctype="multipart/form-data" name="form1" id="form1"
  8.     <div><input type="file" name="file1" /></div> 
  9.     <div><input type="submit" name="Submit" value="提交" /></div> 
  10. </form> 
  11. </body> 
  12. </html> 

5、save.aspx文件,用来处理index.aspx提交的表单

  1. <html> 
  2. <head> 
  3. <meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> 
  4. <title>无标题文档</title> 
  5. </head> 
  6. <body> 
  7. <% 
  8. '取客户端上传的全部文件的集合 
  9.  Dim Files As HttpFileCollection 
  10.  Files = Request.Files 
  11.      
  12. '取当前日期时间 
  13. dim currentdate as Date,strcurrentdate as string 
  14. currentdate=now 
  15. strcurrentdate=currentdate.Millisecond.toString() 
  16. strcurrentdate="000" & strcurrentdate 
  17. strcurrentdate=strcurrentdate.Substring(strcurrentdate.length()-3) 
  18. strcurrentdate=currentdate.toString("yyyyMMddHHmmss") & strcurrentdate 
  19.      
  20. '遍历客户端上传的全部文件 
  21. dim loop1 as Integer=0 
  22.  for loop1 = 0 To (Files.count-1) 
  23.      
  24. dim FileName as string  '文件名 
  25. dim FileType as string  '文件类型 
  26. dim FileSize as long    '文件大小 
  27.              
  28. FileName=Files.item(loop1).FileName 
  29. FileSize=Files.item(loop1).ContentLength 
  30. FileType=Files.item(loop1).ContentType 
  31.          
  32. if FileSize<>0 then '客户端上传了文件 
  33. FileName=Server.MapPath("~/") & strcurrentdate & "_" & (loop1+1) & FileName.Substring(FileName.lastindexof(".")) 
  34. Files.item(loop1).SaveAs(FileName) 
  35. end if 
  36.          
  37. response.write(Filename & "<br>")                
  38. Next loop1 
  39. %> 
  40. </body> 
  41. </html>

6、UploadError.aspx文件 用来显示上传文件超额错误

  1. <html> 
  2. <head> 
  3. <meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> 
  4. <title>无标题文档</title> 
  5. </head> 
  6. <body> 
  7.     <div>出错了,表单不能超过<%=System.Configuration.ConfigurationManager.AppSettings("customMaxRequestLength")%>KB</div>
  8.         <div>[ <a href="index.aspx">返回</a> ]</div>
  9. </body> 
  10. </html> 

     以上代码的关键思路是利用HttpWorkerRequest对象通过GetTotalEntityBodyLength方法先取到整个 HTTP 请求正文的长度,然后进行判断,如果超过了限定值再利用.Net反射调用HttpWorkerRequest的SkipAllPostedContent方法忽略掉HTTP请求的正文,这样服务器就不会缓存Form表单提交的数据,最后再利用.Net反射清除preloadedContent里的数据并将contentLength设置为0,设置完成后跳转到UploadError.aspx页面,显示出错信息,并提示用户系统上传文件的大小限制。经测试此方法与前面利用HttpRequest对象相比处理速度有了很大的提升,而且文件越大效果越明显,在本机上上传50M左右的文件时,处理速度提升了差不多有50%。以下是测试时所使用的Global.ascs代码,有兴趣的可以试试:

  1. <%@ Application Language="VB" %>
  2. <script runat="server">
  3.     
  4.     Protected Sub Application_BeginRequest(ByVal sender As ObjectByVal e As System.EventArgs)        
  5.         Dim mysw As New System.Diagnostics.Stopwatch
  6.         mysw.Start()
  7.         
  8.         '方法1,测试方法1,请将方法2至方法2结束中的代码注释掉
  9.         Dim application As HttpApplication = CType(sender, HttpApplication)
  10.         Dim context As HttpContext = application.Context
  11.         Dim wr As HttpWorkerRequest = GetWorkerRequest()
  12.         
  13.         Dim mybindingflags As System.Reflection.BindingFlags = Reflection.BindingFlags.Instance Or Reflection.BindingFlags.NonPublic
  14.         '取content_type
  15.         Dim content_type As String = application.Request.ContentType
  16.         '只处理enctype为"multipart/form-data" 的Form提交的请求
  17.         If (Not content_type.ToLower().StartsWith("multipart/form-data")) Then Return
  18.         '只处理包含body数据的Request
  19.         If (Not wr.HasEntityBody()) Then Return
  20.         
  21.         '取Request的总长度
  22.         Dim contentlen As Int32 = wr.GetTotalEntityBodyLength()
  23.         If contentlen < (System.Configuration.ConfigurationManager.AppSettings("customMaxRequestLength") * 1024) Then Return
  24.                 
  25.         Dim hct As Type = wr.GetType
  26.         
  27.         hct.GetMethod("SkipAllPostedContent", mybindingflags).Invoke(wr, Nothing)
  28.         hct.GetField("_preloadedContent", mybindingflags).SetValue(wr, Nothing)
  29.         hct.GetField("_contentLength", mybindingflags).SetValue(wr, 0)
  30.         
  31.         '方法1结束
  32.         
  33.         '方法2,测试方法2,请将方法1至方法2结束部分的代码注释掉
  34.         'If Request.ContentLength > (System.Configuration.ConfigurationManager.AppSettings("customMaxRequestLength") * 1024) Then
  35.         
  36.         'End If
  37.         '方法2结束
  38.         
  39.         mysw.Stop()
  40.         context.Response.Write(mysw.ElapsedTicks)
  41.         
  42.         'context.Response.Redirect("~/uploaderror.aspx")
  43.     End Sub
  44.     
  45.     Private Function GetWorkerRequest() As HttpWorkerRequest
  46.         Dim provider As IServiceProvider = HttpContext.Current
  47.         Return CType(provider.GetService(GetType(HttpWorkerRequest)), HttpWorkerRequest)
  48.     End Function
  49. </script>

    很可惜的是利用这个方法限制上传文件的大小还有一点不是很完善的地方,那就是这种方法限制的是整个Form表单数据的大小,并不是实际的文件大小,这两者之间还是有一点点差距的,不过这可以在设置限额的时候留出一定的余量来解决(比如限制10MB,可以将customMaxRequestLength设置为10250,这样就可以留出1MB的余量给Form中的其他表单项),另外就是这种方法还是不能解决"The page cannot be displayed"的问题,不过如果把maxRequest设置为最大的话出现这个问题的概率会小了很多,毕竟没有谁会经常去上传2G以上的文件。

    还有就是在上传大文件的时候,由于网络速度的问题,可能会出现网络连接超时等错误而导致上传的不成功,怎么解决这个问题呢,下一篇中我们会继续讨论。

    本文档中的部分代码参考了 2bno1 及 widebright 的相关文章

    下载本文档的相关代码请点击这里

 

    (补充:http://www.codeplex.com/DevServer/SourceControl/FileView.aspx?itemId=70032&changeSetId=2991这里有HttpRequest对象的源代码,大家可以去看看,另外.Net2005的调试模式下没问题,放到IIS里面"SkipAllPostedContent"出错,再用反射一查HttpWorkerRequest里面没有这个函数了,郁闷……)

--------------------------------------------------------------------------------------------------
PS:本文档为本人原创,如需转载请注明作者及出处。谢谢!
 
原创粉丝点击