1. 程式人生 > >Asp.net WebForm 下載大檔案程式碼記錄

Asp.net WebForm 下載大檔案程式碼記錄

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();
}