1.a标签下载
const elink = document.createElement("a");
elink.download = i.substring(i.lastIndexOf('/')+1);
elink.style.display = "none";
elink.target="_blank";
elink.href = i;
document.body.appendChild(elink);
elink.click();
URL.revokeObjectURL(elink.href); // 释放URL 对象
document.body.removeChild(elink);
必须同源,否则会出现只跳转不下载的情况。
2.直接使用a标签并在url后拼接'?response-content-type=application/octet-stream'字符串就能实现下载。
url = url + "?response-content-type=application/octet-stream"
3.文件流
axios请求:vue记得引入axios
axios.get(i, {responseType: 'blob'}).then(res=>{
console.log(res);
let url=URL.createObjectURL(res.data);
console.log(url);
const a = document.createElement('a');
a.style.display = 'none';
a.href = url;
//download属性可以设置下载到本地时的文件名称,经测试并不需要加文件后缀
a.setAttribute('download', fileName);
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
//释放内存
URL.revokeObjectURL(url);
})
原生请求:
getBlob(url) {
let xhr = new XMLHttpRequest()
let _this = this
xhr.open('get', url, true)
xhr.setRequestHeader('Content-Type', `application/pdf`)
xhr.responseType = 'blob'
xhr.onload = function() {
if (this.status === 200) {
// 接受二进制文件流
// var blob = xhr.response
var blob = this.response
// 下载
_this.downloadExportFile(blob, '文件名', 'pdf')
}
}
xhr.send()
},
downloadExportFile(blobData, fileName, fileType = 'xlsx', callback){
fileName = fileName + '.' + fileType
if (window.navigator.msSaveOrOpenBlob) {
// IE浏览器下
navigator.msSaveBlob(blobData, fileName)
} else {
let link = document.createElement('a')
link.href = window.URL.createObjectURL(blobData)
link.download = fileName
link.click()
window.URL.revokeObjectURL(link.href)
}
if (callback) {
callback()
}
},
如果有文件content:
Download(content, filename) {
var eleLink = document.createElement('a');
eleLink.download = filename;
eleLink.style.display = 'none';
// 字符内容转变成blob地址
var blob = new Blob([content]);
eleLink.href = URL.createObjectURL(blob);
// 触发点击
document.body.appendChild(eleLink);
eleLink.click();
document.body.removeChild(eleLink);
};
4.后端设置下载请求的响应头 Content-Disposition
强制下载
前端只需要 window.open(url) 即可在pc 直接下载