ASP.NET实现从服务器下载文件问题处理

假设在服务器的根目录下有个名为Download的文件夹,这个文件夹存放一些提供给引用程序下载的文件

public void DownloadFile(string path, string name){ try{ System.IO.FileInfo file = new System.IO.FileInfo(path); Response.Clear(); Response.Charset = "GB2312"; Response.ContentEncoding = System.Text.Encoding.UTF8; // 添加头信息,为"文件下载/另存为"对话框指定默认文件名 Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.UrlEncode(name)); // 添加头信息,指定文件大小,让浏览器能够显示下载进度 Response.AddHeader("Content-Length", file.Length.ToString()); // 指定返回的是一个不能被客户端读取的流,必须被下载 Response.ContentType = "application/ms-excel"; // 把文件流发送到客户端 Response.WriteFile(file.FullName); // 停止页面的执行 //Response.End(); HttpContext.Current.ApplicationInstance.CompleteRequest(); } catch (Exception ex){ Response.Write("<script>alert('系统出现以下错误://n" + ex.Message + "!//n请尽快与管理员联系.')</script>"); } }

这个函数是下载功能的组程序,其中path是文件的绝对路径(包括文件名),name是文件名,这个程序是能够运行的.其中如果将HttpContext.Current.ApplicationInstance.CompleteRequest();替换为Response.End(); 就会出现一下错误:异常:由于代码已经过优化或者本机框架位于调用堆栈之上,无法计算表达式的值.但是这个错误不会影响程序的运行,虽然try能够捕捉这个异常(不知道为什么)

在网上找了一些这个问题产生的原因:如果使用 Response.End、Response.Redirect 或 Server.Transfer 方法,将出现ThreadAbortException 异常。您可以使用 try-catch 语句捕获此异常。Response.End 方法终止页的执行,并将此执行切换到应用程序的事件管线中Application_EndRequest 事件。不执行 Response.End 后面的代码行。此问题出现在 Response.Redirect 和 Server.Transfer 方法中,因为这两种方法均在内部调用 Response.End。

提供的解决方法有:

要解决此问题,请使用下列方法之一:

对于 Response.End,调用 HttpContext.Current.ApplicationInstance.CompleteRequest() 方法而不是 Response.End 以跳过 Application_EndRequest 事件的代码执行。

对于 Response.Redirect,请使用重载 Response.Redirect(String url, bool endResponse),该重载对 endResponse 参数传递 false 以取消对 Response.End 的内部调用。例如:

Response.Redirect ("nextpage.aspx", false); catch (System.Threading.ThreadAbortException e){ throw; } 接下来就可以通过其他函数或者事件调用这个函数来下载服务器上的文件了 protected void btnOutput_Click(object sender, EventArgs e){ try{ string strPath = Server.MapPath("https://www.jb51.net/") + "Download//学生基本信息模版.xls"; DownloadFile(strPath, "学生基本信息模版.xls"); } catch (Exception exp){ Response.Write("<script>alert('系统出现以下错误://n" + exp.Message + "!//n请尽快与管理员联系.')</script>"); } }

从这个事件可以看出DownloadFile函数的第一个参数为文件的绝对路径不然程序会报错。

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wdpsdf.html