前段时间需要实现ASP.NET下载文件,如何实现ASP.NET下载文件? 在原文找到了答案,果断转载过来收藏,只试过第一种方式~

 1 /*
 2 微软为Response对象提供了一个新的方法TransmitFile来解决使用Response.BinaryWrite
 3 下载超过400mb的文件时导致Aspnet_wp.exe进程回收而无法成功下载的问题。
 4 代码如下:
 5 */
 6 
 7 Response.ContentType = "application/x-zip-compressed";
 8 Response.AddHeader("Content-Disposition", "attachment;filename=z.zip");
 9 string filename = Server.MapPath("DownLoad/aaa.zip");
10 Response.TransmitFile(filename);

方式一

 1 //using System.IO;
 2 string fileName = "aaa.zip";//客户端保存的文件名
 3 string filePath = Server.MapPath("DownLoad/aaa.zip");//路径
 4 
 5 FileInfo fileInfo = new FileInfo(filePath);
 6 Response.Clear();
 7 Response.ClearContent();
 8 Response.ClearHeaders();
 9 Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName);
10 Response.AddHeader("Content-Length", fileInfo.Length.ToString());
11 Response.AddHeader("Content-Transfer-Encoding", "binary");
12 Response.ContentType = "application/octet-stream";
13 Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
14 Response.WriteFile(fileInfo.FullName);
15 Response.Flush();
16 Response.End();

方式二

 1 string fileName = "aaa.zip";//客户端保存的文件名
 2 string filePath = Server.MapPath("DownLoad/aaa.zip");//路径
 3 
 4 System.IO.FileInfo fileInfo = new System.IO.FileInfo(filePath);
 5 
 6 if (fileInfo.Exists == true)
 7 {
 8     const long ChunkSize = 102400;//100K 每次读取文件,只读取100K,这样可以缓解服务器的压力
 9     byte[] buffer = new byte[ChunkSize];
10 
11     Response.Clear();
12     System.IO.FileStream iStream = System.IO.File.OpenRead(filePath);
13     long dataLengthToRead = iStream.Length;//获取下载的文件总大小
14     Response.ContentType = "application/octet-stream";
15     Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName));
16     while (dataLengthToRead > 0 && Response.IsClientConnected)
17     {
18         int lengthRead = iStream.Read(buffer, 0, Convert.ToInt32(ChunkSize));//读取的大小
19         Response.OutputStream.Write(buffer, 0, lengthRead);
20         Response.Flush();
21         dataLengthToRead = dataLengthToRead - lengthRead;
22     }
23     Response.Close();
24 }

方式三

 1 string fileName = "aaa.zip";//客户端保存的文件名
 2 string filePath = Server.MapPath("DownLoad/aaa.zip");//路径
 3 
 4 //以字符流的形式下载文件
 5 FileStream fs = new FileStream(filePath, FileMode.Open);
 6 byte[] bytes = new byte[(int)fs.Length];
 7 fs.Read(bytes, 0, bytes.Length);
 8 fs.Close();
 9 Response.ContentType = "application/octet-stream";
10 //通知浏览器下载文件而不是打开
11 Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
12 Response.BinaryWrite(bytes);
13 Response.Flush();
14 Response.End();

方式四

版权声明:本文为Chendaqian原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/Chendaqian/p/3377869.html