在我们的系统的编写过程中,应该有很多的时候需要客户下载文件.我第一次的做法(应该也是大部分人的做法吧?)是:
1 httpresponse response = httpcontext.current.response;
2 string js = "<script language=javascript>window.open('{0}');</script>";
3 js = string.format(js, url);
4 response.write(js);
51/**//// <summary>
2 /// 下载文件
3 /// </summary>
4 /// <param name="filename">文件物理地址</param>
5
6protected void downloadfile(string filename)
7 {
8 string savefilename = "test.xls";
9 int intstart = filename.lastindexof("\\")+1;
10 savefilename = filename.substring(intstart,filename.length-intstart);
11 filestream myfilestream;
12 long filesize;
13
14 myfilestream = new filestream(filename,filemode.open);
15 filesize = myfilestream.length;
16
17 byte[] buffer = new byte[(int)filesize];
18 myfilestream.read(buffer, 0, (int)filesize);
19 myfilestream.close();
20
21 response.addheader("content-disposition", "attachment;filename="+savefilename);
22 response.contentencoding = system.text.encoding.getencoding("gb2312");
23 response.contenttype = "application/vnd.ms-excel";
24
25 response.binarywrite(buffer);
26 response.flush();
27 response.close();
28 response.end();
29
30 }
31
但是有个严重的问题,就是文件格式。这样只是将流输出,且无法正确识别格式。还好,能人层出不穷, 柚子nan 提出了能否不考虑文件的类型,直接把文件显示到浏览器(response) 的想法正好切中我的要害所在,于是急忙研究了柚子nan的想法,修改出最后代码:
1 /**//// <summary>
2 /// 下载文件
3 /// </summary>
4 /// <param name="filename">文件物理地址</param>
5 protected void downloadfile(string filename)
6 {
7 string savefilename = "test.xls";
8 int intstart = filename.lastindexof("\\")+1;
9 savefilename = filename.substring(intstart,filename.length-intstart);
10
11 response.clear();
12 response.charset = "utf-8";
13 response.buffer= true;
14 this.enableviewstate = false;
15 response.contentencoding = system.text.encoding.utf8;
16
17 response.appendheader("content-disposition","attachment;filename=" + savefilename);
18 response.writefile(filename);
19 response.flush();
20 response.close();
21
22 response.end();
23 }
-
Copyright © 2001- 2010 丰搜网 All Rights Reserved
- ICP备案编号:粤ICP备06052964号
Java Asp PHP .Net XML C/C++ CGI VB Jsp J2ee J2se J2me EJB Servlet Tomcat Resin Struts Weblogic Eclipse ANT GUI JMS Web servise IDEA Webphere Hibernate Spring Jboss Applet Swing Socket Javamail Perl Ajax P2P 安全 模式 框架 测试 开源 游戏
Windows XP Windows 2000 Windows 2003 Windows Me Windows 9.x Linux UNIX 注册表 操作系统 服务器 应用服务器