一,直接使用
download() {
const link = document.createElement("a");
link.style.display = "none";
//请求后台的具体地址
link.href ="http://192.168.5.69:8000/api1/cardGiveBatchEntity/account/template/download";
link.setAttribute("download", "文件名称.xlsx");
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
二,线上pdf链接下载
downTicket() {
let url = url
if (!url) return
// 获取文件名
let fileName = this.urlFile(url, 1);
// 获取文件后缀
let fileExtension = this.urlFile(url, 2);
let xhr = new XMLHttpRequest();
xhr.open('get', url, true);
xhr.setRequestHeader('Content-Type', `application/${fileExtension}`);
xhr.responseType = "blob";
xhr.onload = function () {
if (this.status == 200) {
//接受二进制文件流
console.log(this)
var blob = this.response;
const blobUrl = window.URL.createObjectURL(blob);
// 这里的文件名根据实际情况从响应头或者url里获取
const a = document.createElement('a');
a.href = blobUrl;
a.download = fileName;
a.click();
window.URL.revokeObjectURL(blobUrl);
}
}
xhr.send();
},
urlFile(url, type) {
let filename = url.substring(url.lastIndexOf('/') + 1)
switch (type) {
case 1: return filename; break;
case 2: return filename.substring(filename.lastIndexOf(".") + 1); break;
case 3: return filename.substring(0, filename.lastIndexOf(".")); break;
case 4: return url.substring(0, url.lastIndexOf('/') + 1)
}
},
三,vue中使用文件流进行下载(new Blob)
get请求获取
axios({
url: "/cardGiveBatchEntity/account/template/download",
method: "get",
//vue axios(下载文件流)设置返回值类型responseType:‘blob‘
responseType: "blob",
})
.then((res) => {
console.log(res);
//解析文件充blod中解析
const url = window.URL.createObjectURL(
new Blob([res.data], { type: "application/vnd.ms-excel" })
);
const link = document.createElement("a");
link.style.display = "none";
link.href = url;
link.setAttribute("download", "文件名称.xlsx");
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
})
.catch((err) => {
console.log(err);
});
由于get可以如此用,
var params={ XX:xx, }
this.$axios.get('/XXX/XXX',{
params: params,
responseType: 'blob'
}).then(res => {
console.log(res);
});
若是封装的话则使用:
post请求获取
axios
.post("/cardGiveBatchEntity/account/template/download", "", {
headers: {},
responseType: "blob",
})
.then((res) => {
console.log(res);
const url = window.URL.createObjectURL(
new Blob([res.data], { type: "application/vnd.ms-excel" })
);
const link = document.createElement("a");
link.style.display = "none";
link.href = url;
link.setAttribute("download", "文件名称.xlsx");
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
})
.catch((err) => {
console.log(err);
});
post封装的操作: