js实现下载文件
【downloadUtils.js】
//方案1:根据url下载文件(经测试这种方案无法重命名文件!!!)
export function downloadByUrl(url, filename) {
const link = document.createElement("a");
link.style.display = "none";
// 设置下载地址
link.setAttribute("href", url);
// 设置文件名
link.setAttribute("download", filename);
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
//方案2:使用 blob 数据类型方式(推荐)
export function downloadByBlob(downloadUrl, downloadFileName) {
getBlob(downloadUrl).then((blob) => {
saveAs(blob, downloadFileName);
});
}
function getBlob(url) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.responseType = "blob";
xhr.onload = () => {
if (xhr.status === 200) {
resolve(xhr.response);
} else {
reject(new Error(`Request failed with status ${xhr.status}`));
}
};
xhr.onerror = () => {
reject(new Error("Request failed"));
};
xhr.send();
})
}
function saveAs(blob, filename) {
const link = document.createElement("a");
const body = document.body;
link.href = window.URL.createObjectURL(blob);
link.download = filename;
// hide the link
link.style.display = "none";
body.appendChild(link); //解决火狐无法触发
link.click();
body.removeChild(link);
window.URL.revokeObjectURL(link.href);
}

