首页 > 代码库 > 文件下载(适用于各个浏览器)

文件下载(适用于各个浏览器)

1、cs代码

 1 public void DownFile(string filePath ,string fileName )
 2 {
 3  // filePath  文件路径 例如:/File/记录.xlsx 
 4 
 5  // fileName  文件名称 例如:记录.xlsx (要后缀哦)
 6 Encoding encoding; // 申明编码
 7 string outputFileName; // 输出名字
 8 Debug.Assert(HttpContext.ApplicationInstance.Request.UserAgent != null, "HttpContext.ApplicationInstance.Request.UserAgent != null");
 9 string browser = HttpContext.ApplicationInstance.Request.UserAgent.ToUpper();
10 // 微软的浏览器和ie过滤
11 if (browser.Contains("MS") && browser.Contains("IE"))
12 {
13 outputFileName = HttpUtility.UrlEncode(filePath);
14 encoding = Encoding.Default;
15 }
16 //火狐
17 else if (browser.Contains("FIREFOX"))
18 {
19 outputFileName = fileName;
20 encoding = Encoding.GetEncoding("GB2312");
21 }
22 else
23 {
24 outputFileName = HttpUtility.UrlEncode(fileName);
25 encoding = Encoding.Default;
26 }
27 
28 string absoluFilePath = Server.MapPath(filePath); //获取上传文件路径
29 FileStream fs = new FileStream(absoluFilePath, FileMode.Open);
30 byte[] bytes = new byte[(int)fs.Length];
31 fs.Read(bytes, 0, bytes.Length);
32 fs.Close(); //关闭流,释放资源
33 HttpContext.ApplicationInstance.Response.Clear();
34 HttpContext.ApplicationInstance.Response.Buffer = true;
35 HttpContext.ApplicationInstance.Response.ContentEncoding = encoding;
36 HttpContext.ApplicationInstance.Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}", string.IsNullOrEmpty(outputFileName) ? DateTime.Now.ToString("yyyyMMddHHmmssfff") : outputFileName));
37 Response.BinaryWrite(bytes);
38 Response.Flush();
39 HttpContext.ApplicationInstance.Response.End();
40 }

2、html代码

前端HTML 写一个a标签就好:如 <a href=http://www.mamicode.com/DownFile target=_blank>文件下载</a>

 

文件下载(适用于各个浏览器)