在我们的系统的编写过程中,应该有很多的时候需要客户下载文件.我第一次的做法(应该也是大部分人的做法吧?)是:
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);
5
但是有个问题了,就是会被广告拦截软件直接拦截掉,另我非常的头痛,于是寻找更好的解决方法.看了用Response.BinaryWrite写文件流一文之后觉得确实可以如此,修改代码如下:
1/**//// <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 }