1.window.open下载
window.open(url)
//或者
window.location.href = url
2.iframe标签下载
const iframe = document.createElement('iframe');
iframe.style.display = 'none';
iframe.src = url;
document.body.appendChild(iframe);
setTimeout(() => {
document.body.removeChild(iframe);
}, 200);
3.a标签下载
1.单个下载
download(file) {
let aLink = document.createElement('a'); // 创建a标签
aLink.href = file.url+ '?response-content-type=application/octet-stream';//加后缀任何链接都会下载,而不是预览
aLink.download = file.name;
// console.log(aLink.download)
document.body.appendChild(aLink);
aLink.click();
document.body.removeChild(aLink);
},
2.多个下载
DownLoadData() {
for (let i in this.fileList) {
setTimeout(() => {
this.download(this.fileList[i]);
}, i * 500);
}
},
download(file) {
let aLink = document.createElement('a'); // 创建a标签
aLink.href = file.url+ '?response-content-type=application/octet-stream';
aLink.download = file.name;
// console.log(aLink.download)
document.body.appendChild(aLink);
aLink.click();
document.body.removeChild(aLink);
},
4.下载并改名字
正常来说更改download属性就可以更改名字,但是当下载链接跨域时就download就不会生效,因为浏览器无法获取到文件,不能对他进行更改
所以我们使用get请求获取到blob文件,转换为本地的链接然后下载,就可以复制download属性下载
download(file) {
//下载
var x = new XMLHttpRequest();
x.open('GET', file.url, true);
x.responseType = 'blob';
x.onload = function(e) {
var url = window.URL.createObjectURL(x.response);
const link = document.createElement('a');
link.target = '_blank';
link.href = url;
link.download = file.name;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
};
x.send();
},
5.下载txt文件乱码解决
download(file) {
const req = new XMLHttpRequest();
req.open('get', file.url, true);
req.responseType = 'blob';
req.setRequestHeader('Content-Type', 'application/json');
req.onload = function() {
// 这里因为没有对返回的数据处理编码格式,所以在预览txt时需要转换成utf-8
const data = new Blob([req.response], { type: 'application/json;charset=utf-8' });
let blobUrl = window.URL.createObjectURL(data);
window.open(blobUrl);
};
req.send();
},