前端根据后台返回的文件地址(非跨域),实现点击下载文件
a 标签下载文件,download属性可以实现对下载文件的重命名
<a download="文件名称" href="文件地址">下载</a>
在Chrome浏览器中,使用a标签属性download下载pdf链接文件,如果是相同域时,可以直接下载;跨域会直接打开页面预览文件;
IE浏览器下 download 修改文件名失效
修改:
//文件地址非跨域
<a href="javascript:void(0)" onClick={()=>this.download(url)}>下载</a>
js
getBlob = (url) => {
return new Promise(resolve => {
const xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'blob';
xhr.onload = () => {
if (xhr.status === 200) {
resolve(xhr.response);
}
};
xhr.send();
});
}
saveAs = (blob, filename) => {
if (window.navigator.msSaveOrOpenBlob) {
navigator.msSaveBlob(blob, filename);
} else {
const link = document.createElement('a');
const body = document.querySelector('body');
link.href = window.URL.createObjectURL(blob);
link.download = filename;
// fix Firefox
link.style.display = 'none';
body.appendChild(link);
link.click();
body.removeChild(link);
window.URL.revokeObjectURL(link.href);
}
}
download = (url) => {
let filename="xxxxx";
this.getBlob(url).then(blob => {
this.saveAs(blob, filename);
});
}
参考:
https://www.cnblogs.com/jackson-yqj/p/11321275.html
https://blog.csdn.net/borage21/article/details/108253737
https://www.cnblogs.com/ygunoil/p/12565565.html