js下載流文件


js代碼:

//  獲取時間戳
let timestamp = new Date().getTime();
// 獲取XMLHttpRequest
let xmlResquest = new XMLHttpRequest();
//  發起請求
xmlResquest.open("GET", `${API}/export/exportCheckingIn?uuid=${params.name}&startTime=${params.startTime}&endTime=${params.endTime}`, true);
// 設置請求頭類型
xmlResquest.setRequestHeader("Content-type", "application/json");
//  設置請求token
// xmlResquest.setRequestHeader(
 
// );
xmlResquest.responseType = "blob";
//  返回
xmlResquest.onload = function (oEvent) {
    let content = xmlResquest.response;
    // 組裝a標簽
    let elink = document.createElement("a");
    // 設置下載文件名
    elink.download = timestamp + ".xlsx";
    elink.style.display = "none";
    let blob = new Blob([content]);
    elink.href = URL.createObjectURL(blob);
    document.body.appendChild(elink);
    elink.click();
    document.body.removeChild(elink);
};

xmlResquest.send();

c#后台代碼:

        public static HttpResponseMessage Download(string filePath)
        {
            string fullPath = BasePath + filePath;

            string fileName = Path.GetFileName(fullPath);
            FileStream fileStream = new FileStream(fullPath, FileMode.Open);

            HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
            response.Content = new StreamContent(fileStream);

            response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");

            MediaTypeHeaderValue contentType = response.Content.Headers.ContentType;
            response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
            {
                FileName = HttpUtility.UrlEncode(fileName)
            };

            response.Headers.Add("Access-Control-Expose-Headers", "FileName");
            response.Headers.Add("FileName", HttpUtility.UrlEncode(fileName));

            return response;
        }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM