文件下载 方法一
function downloadFile() {
const link = document.createElement('a');
link.style.display = 'none';
link.setAttribute('href', file.sourceUrl); // 设置下载地址
link.setAttribute('download', file.fileName); // 设置文件名
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
文件下载 方法二
async function download(downloadUrl, downloadFileName) {
const blob = await getBlob(downloadUrl);
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) {
if (window.navigator.msSaveOrOpenBlob) {
navigator.msSaveBlob(blob, filename);
} else {
let link = document.createElement('a');
const body = document.body;
link.href = window.URL.createObjectURL(blob);
link.download = filename;
link.style.display = 'none'; // hide the link
body.appendChild(link);
link.click();
body.removeChild(link);
window.URL.revokeObjectURL(link.href);
}
}