C# 流方式下載檔案
阿新 • • 發佈:2019-02-01
//客戶端儲存的檔名 string fileName = "222.xls"; //被下載檔案的伺服器絕對路徑 string filePath = Server.MapPath("file/" + doc.FileName); Response.Clear(); //清空快取 //以字元流的形式下載檔案 FileStream fs = new FileStream(filePath, 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)); Response.BinaryWrite(bytes); Response.Flush(); //下載完成後刪除檔案 File.Delete(Server.MapPath("file/" + doc.FileName)); Response.End();