Vue下载文件之文件流
{% note success %}
后端返回文件流,vue下载到本地
请求时需要设置 responseType: "blob"
,否则下载pdf文件打开会为空
操作
必须 responseType: "blob"
,不然下载的pdf
为空白
// getDownFile
export function getDownFile (url, parameter) {
return axios({
url: url,
method: "get",
params: parameter,
// 下载pdf空白问题
responseType: "blob"
});
}
Vue
组件中使用
handleExportXls(fileName) {
if (!fileName || typeof fileName !== "string") {
fileName = "导出文件";
}
getDownFile("后端地址", 需要传的参数).then((data) => {
if (!data) {
this.$message.warning("文件下载失败");
return;
}
if (typeof window.navigator.msSaveBlob !== "undefined") {
window.navigator.msSaveBlob(new Blob([data]), fileName + ".xlsx");
} else {
const url = window.URL.createObjectURL(new Blob([data]));
const link = document.createElement("a");
link.style.display = "none";
link.href = url;
link.setAttribute("download", fileName + ".xlsx");
document.body.appendChild(link);
link.click();
document.body.removeChild(link); // 下载完成移除元素
window.URL.revokeObjectURL(url); // 释放掉blob对象
}
});
}
其他写法参考
https://www.jianshu.com/p/f7e3477d7182
const filename = response.headers['content-disposition'].match(
/filename=(.*)/
)[1]
// 首先要创建一个 Blob 对象(表示不可变、原始数据的类文件对象)
const blob = new Blob([response.data], {type: 'application/zip'});
// or const blob = new File([response.data], fileName);
if (typeof window.navigator.msSaveBlob !== 'undefined') {
// 兼容IE,window.navigator.msSaveBlob:以本地方式保存文件
window.navigator.msSaveBlob(blob, decodeURI(filename))
} else {
let elink = document.createElement("a"); // 创建一个<a>标签
elink.style.display = "none"; // 隐藏标签
elink.href = window.URL.createObjectURL(blob); // 配置href,指向本地文件的内存地址
elink.download = filename;
elink.click();
URL.revokeObjectURL(elink.href); // 释放URL 对象
document.body.removeChild(elink); // 移除<a>标签
}
https://blog.csdn.net/weixin_43928792/article/details/122881900
//url请求参数
//params请求参数
//filename文件名称
export function download(url, params, filename) {
return service
.post(url, params, {
transformRequest: [
// (params) => {
// return tansParams(params);
// },
],
headers: {
"Content-Type": "application/json;charset=utf-8",
//"Content-Type": "application/x-www-form-urlencoded",
},
responseType: "blob",//关键
})
.then((data) => {
console.log(data);
const content = data;
const blob = new Blob([content]);
if ("download" in document.createElement("a")) {
const elink = document.createElement("a");
elink.download = filename;
elink.style.display = "none";
elink.href = URL.createObjectURL(blob);
document.body.appendChild(elink);
elink.click();
URL.revokeObjectURL(elink.href);
document.body.removeChild(elink);
} else {
navigator.msSaveBlob(blob, filename);
}
})
.catch((r) => {
console.error(r);
});
}