在我们的系统的编写过程中,应该有很多的时候需要客户下载文件.我第一次的做法(应该也是大部分人的做法吧?)是:
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 } 但是有个严重的问题,就是文件格式。这样只是将流输出,且无法正确识别格式。还好,能人层出不穷, 柚子Nan 提出了能否不考虑文件的类型,直接把文件显示到 |