场景:通过接口获取文件信息,再动态生成a标签,添加href、download,点击文件下载后,文件名并不是设置的download
问题:接口返回数据的文件url域名跟当前系统域名不一致,导致download失效
解决方案:采用原生请求设置responseType来实现指定download下载
<div @click="download">点击下载</div>
...
download () {
axios.post().then(res => {
// res.fileUrl: 'http://127.0.0.1/files/123456.xlsx'
// res.fileName: '表格.xlsx'
const xhr = new XMLHttpRequest();
xhr.open('GET', res.fileUrl, true);
xhr.responseType = 'blob';
xhr.onload = () => {
const url = window.URL.createObjectURL(xhr.response);
const a = document.createElement('a');
a.href = url;
a.download = res.fileName;
a.click();
a.remove();
}
xhr.send();
})
}