js代碼html
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> <script src="Scripts/jquery-3.3.1.js"></script> <script> function download() { var url = '/Order/DownloadResource?o=90&t=bf32a13f4701473a9385896f5578953d'; var xhr = new XMLHttpRequest(); xhr.open('POST', url, true); // 也可使用POST方式,根據接口 xhr.responseType = "blob"; // 返回類型blob xhr.onload = function () { if (this.status === 200) { var blob = this.response; var reader = new FileReader(); reader.readAsDataURL(blob); // 轉換爲base64,能夠直接放入a表情href reader.onload = function (e) { var a = document.createElement('a'); a.download = 'data.rar';//下載文件名 a.href = e.target.result; $("body").append(a); // 修復firefox中沒法觸發click a.click(); $(a).remove(); } } }; // 發送ajax請求 xhr.send() } </script> </head> <body> <input type="button" value="下載" onclick="download()" /> </body> </html>
後臺代碼jquery
[HttpPost] public void Download(string o, string t) { string filePath = @"D:\Download\排期(20190412).xlsx"; #region 處理下文件 var arr= filePath.Split('\\'); string fileName = arr[arr.Length-1]; 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(); Response.End(); } #endregion }