重点:
跨域问题:如果当前页面地址和预下载的文件所处服务器不在同一域名下,由于跨域访问限制,download配置会不生效。可以使用blob方式将文件转为同源文件,再进行配置和下载
方法如下
const downloadExcel = async(fileUrl,fileName) => {
try {
const response = await axios.get(fileUrl, { responseType: 'blob' });
const contentType = response.headers['content-type'];
const blob = new Blob([response.data], { type: contentType });
if (typeof window.navigator.msSaveBlob !== 'undefined') {
// 兼容IE浏览器
window.navigator.msSaveBlob(blob, fileName);
} else {
const url = window.URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', fileName);
link.style.display = 'none';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
window.URL.revokeObjectURL(url);
}
} catch (error) {
console.error('Error downloading file:', error);
}
}