Asp.Net 之 下载文件的常用方式
1、直接使用Response.TransmitFile(filename)方法
protected void Button_Click(object sender, EventArgs e) { /* 微软为Response对象提供了一个新的方法TransmitFile来解决使用Response.BinaryWrite 下载超过400mb的文件时导致Aspnet_wp.exe进程回收而无法成功下载的问题。 代码如下: */ Response.ContentType = "application/x-zip-compressed"; Response.AddHeader("Content-Disposition", "attachment;filename=z.zip"); string filename = Server.MapPath("DownLoad/aaa.zip"); //将指定的文件直接写入 HTTP 响应输出流,而不在内存中缓冲该文件。 Response.TransmitFile(filename); }
2、WriteFile实现下载
protected void Button_Click(object sender, EventArgs e) { /* using System.IO; */ string fileName = "aaa.zip";//服务端保存的文件名 string filePath = Server.MapPath("DownLoad/aaa.zip");//路径 System.IO.FileInfo fileInfo = new System.IO.FileInfo(filePath); Response.Clear(); Response.ClearContent(); Response.ClearHeaders(); Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName); Response.AddHeader("Content-Length", fileInfo.Length.ToString()); Response.AddHeader("Content-Transfer-Encoding", "binary"); Response.ContentType = "application/octet-stream"; Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312"); //将指定文件的内容作为文件块直接写入 HTTP 响应输出流。 Response.WriteFile(fileInfo.FullName); Response.Flush(); Response.End(); }
3、WriteFile分块下载
protected void Button_Click(object sender, EventArgs e) { string fileName = "aaa.zip";//服务端保存的文件名 string filePath = Server.MapPath("DownLoad/aaa.zip");//路径 System.IO.FileInfo fileInfo = new System.IO.FileInfo(filePath); if (fileInfo.Exists == true) { const long ChunkSize = 102400;//100K 每次读取文件,只读取100K,这样可以缓解服务器的压力 byte[] buffer = new byte[ChunkSize]; Response.Clear(); System.IO.FileStream iStream = System.IO.File.OpenRead(filePath); long dataLengthToRead = iStream.Length;//获取下载的文件总大小 Response.ContentType = "application/octet-stream"; Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName)); while (dataLengthToRead > 0 && Response.IsClientConnected) { //从流中读取字节块并将该数据写入给定缓冲区中 //返回结果:读入缓冲区中的总字节数。 //如果当前的字节数没有所请求那么多,则总字节数可能小于所请求的字节数;如果已到达流的末尾,则为零。 int lengthRead = iStream.Read(buffer, 0, Convert.ToInt32(ChunkSize));//读取的大小 //当在派生类中重写时,向当前流中写入字节序列,并将此流中的当前位置提升写入的字节数。 Response.OutputStream.Write(buffer, 0, lengthRead); Response.Flush(); dataLengthToRead = dataLengthToRead - lengthRead; } Response.Close(); } }
4、流方式下载
protected void Button4_Click(object sender, EventArgs e) { string fileName = "aaa.zip";//服务端保存的文件名 string filePath = Server.MapPath("DownLoad/aaa.zip");//路径 //以字符流的形式下载文件 System.IO.FileStream fs = new System.IO.FileStream(filePath, System.IO.FileMode.Open); byte[] bytes = new byte[(int)fs.Length]; fs.Read(bytes, 0, bytes.Length); fs.Close(); Response.ContentType = "application/octet-stream"; //通知浏览器下载文件而不是打开 Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8)); //将一个二进制字符串写入 HTTP 输出流 Response.BinaryWrite(bytes); Response.Flush(); Response.End(); }