日期:2014-05-18 浏览次数:21011 次
protected void Application_BeginRequest(object sender, EventArgs e) { HttpRuntimeSection runTime = (HttpRuntimeSection)WebConfigurationManager.GetSection("system.web/httpRuntime"); int maxRequestLength = (runTime.MaxRequestLength - 100) * 1024; HttpContext context = ((HttpApplication)sender).Context; if (Request.ContentLength > maxRequestLength) { IServiceProvider provider = (IServiceProvider)context; HttpWorkerRequest 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); } } } } protected void Application_Error(object sender, EventArgs e) { Exception ex = Server.GetLastError(); if (ex.InnerException != null && ex.InnerException.Message.Contains("Maximum request length exceeded")) { Server.ClearError(); Response.Redirect("~/FileTooLarge.aspx"); } }
------解决方案--------------------
从实用角度出发,asp.net没有这个能力。
这需要使用sivlerlight或者ActiveX插件等来实现上传。例如当用户把本地文件用鼠标拖拽到silverlight程序上的时候,silverlight程序就可以立刻检查文件的大小,甚至对文件内容做一些过滤和转换、压缩,然后才开始上传到服务器。由于这些动作在客户端完成,于是可以及时处理。
而假设你等着浏览器使用什么<input type=file />这种东西把大文件传送给服务器的过程中最后才报告“文件太大”,实在是已经太晚了。