日期:2014-05-18  浏览次数:20954 次

asp.net中c# 怎么做当上传打文件时提示上传文件太大不能上次
上传小文件是成功的。但是当上传大文件的时候直接连程序都不能进去。出异常。也不能弹出“文件太大”的messagebox了
所以我想实现设置只能实现上传小于10mb的 ,当上传大于10mb时跳出一个提示窗口说文件太大。不要连程序都进不去。
求大家想办法。给出程序。或相关链接


------解决方案--------------------
不好意思,上面没有说清楚,详细的代码如下:

C# code

        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 />这种东西把大文件传送给服务器的过程中最后才报告“文件太大”,实在是已经太晚了。