当前位置: 移动技术网 > IT编程>开发语言>.net > ASP.NET实现从服务器下载文件问题处理

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

2017年12月08日  | 移动技术网IT编程  | 我要评论

大汉封禅,广深铁路美股,美女睡地板小游戏

假设在服务器的根目录下有个名为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("/") + "download//学生基本信息模版.xls";
  downloadfile(strpath, "学生基本信息模版.xls");
 }
 catch (exception exp){
  response.write("<script>alert('系统出现以下错误://n" + exp.message + "!//n请尽快与管理员联系.')</script>");
 }
 } 

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

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持移动技术网!

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网