在实际项目开发中经常会遇到下载文件的情况,总结下来,以备不时之需。
字节流下载
protected void btnDownload_Click(object sender, EventArgs e)
{
//下载到客户端后显示的文件名
string fileName = "蝈蝈.xls";
//服务器目标文件
string filePath = Server.MapPath("UploadFiles/awesome.xls");
//以字符流的形式下载文件
FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
//每次读取1MB
byte[] bytes = new byte[1024 * 1024];
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
//读取到的字节长度
int length = 0;
do
{
length = fs.Read(bytes, 0, bytes.Length);
Response.BinaryWrite(bytes);
} while (length == 1024 * 1024);
Response.Flush();
fs.Close();
Response.End();
}
读取完毕后有可能出现下载的文件比原文件略大的情况,举例说明:
原文件1.5MB,第一次读了1MB,Response.BinaryWrite()输出1MB,第二次读了0.5MB,但是Response.BinaryWrite()仍然输出1MB,所以造成了比原文件略大的情况,不过不影响文件的完整度,所以可放心使用。