protected void DownloadFile(){
const long ChunkSize = 1024 * 100;//100K 每次读取文件,只读取100k
string filepath = "F:\\Win桌面主题\\1501216057239.jpg";
string filename = System.IO.Path.GetFileName(filepath);
using (System.IO.FileStream stream = System.IO.File.OpenRead(filepath))
{
stream.Position = 0;
if (stream.Length <= 0) return;
byte[] buffer = new byte[ChunkSize];
string downloadFilename = filename;
Response.Clear();
Response.ClearContent();
long dataLengthToRead = stream.Length;//获取下载的文件总大小
//Response.ContentType = "application/application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition", $"attachment; filename='{HttpUtility.UrlEncode(downloadFilename).Replace("+", "%20")}'");
//Response.AddHeader("Content-Length", stream.Length.ToString());
while (dataLengthToRead > 0 && Response.IsClientConnected)
{
int lengthRead = stream.Read(buffer, 0, Convert.ToInt32(ChunkSize));//读取的大小
Response.OutputStream.Write(buffer, 0, lengthRead);
Response.Flush();
dataLengthToRead = dataLengthToRead - lengthRead;
}
}
//关闭响应,防止页面内容写入文件。
//不能用Response.End()方法来结束流,因为会抛ThreadAboutException
Response.Close();
}
Asp.net WebForm 下载大文件代码记录
猜你喜欢
转载自blog.csdn.net/marshal1991415/article/details/84180274
今日推荐
周排行