【前端】文件下载重命名
原创
©著作权归作者所有:来自51CTO博客作者我是Superman丶的原创作品,请联系作者获取转载授权,否则将追究法律责任
同域下
var link = document.createElement('a');
link.href = file.url;
link.download = file.name;
link.target="_blank";
link.click();
跨域下
function load(file) {
this.getBlob(file.url).then(blob => {
this.saveAs(blob, file.name);
});
}
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) {
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = filename;
link.click();
}