js實現文件流下載文件


以下2個函數實現:函數一位原生ajax將請求的響應數據類型設置為blob,函數二是創建blob對象實現文件下載

// http請求函數,支持配置請求和響應參數
function ajaxRequest(method, url, type) {
return new Promise((resolve, reject) => {
const req = new XMLHttpRequest();
req.open(method, url, true);
req.responseType = type;
req.onreadystatechange = () => {
// readyState == 4說明請求已完成
if (req.readyState === 4) {
const data = req.response;
// 獲取文件名
const content = req.getResponseHeader('Content-Disposition');
const fileName = content && content.split(';')[1].split('filename=')[1];
if (req.status === 200 || req.status === 304) {
resolve({data, fileName});
}
else {
reject(data);
}
}
};
// 發送數據
req.send();
});
}

 

// 文件流轉blob對象下載
function downloadFile(data, type, fileName) {
let blob = new Blob([data], {type: `application/${type};charset=utf-8`});
// 獲取heads中的filename文件名
let downloadElement = document.createElement('a');
// 創建下載的鏈接
let href = window.URL.createObjectURL(blob);
downloadElement.href = href;
// 下載后文件名
downloadElement.download = fileName;
document.body.appendChild(downloadElement);
// 點擊下載
downloadElement.click();
// 下載完成移除元素
document.body.removeChild(downloadElement);
// 釋放掉blob對象
window.URL.revokeObjectURL(href);
}

 


免責聲明!

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



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