后端返回文件流,vue下载到本地
请求时需要设置 responseType: "blob"
,否则下载pdf文件打开会为空
操作
必须 responseType: "blob"
,不然下载的pdf
为空白
1 2 3 4 5 6 7 8 9 10
| export function getDownFile (url, parameter) { return axios({ url: url, method: "get", params: parameter, responseType: "blob" }); }
|
Vue
组件中使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| 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); } }); }
|
其他写法参考
https://www.jianshu.com/p/f7e3477d7182
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| const filename = response.headers['content-disposition'].match( /filename=(.*)/ )[1]
const blob = new Blob([response.data], {type: 'application/zip'});
if (typeof window.navigator.msSaveBlob !== 'undefined') { window.navigator.msSaveBlob(blob, decodeURI(filename)) } else { let elink = document.createElement("a"); elink.style.display = "none"; elink.href = window.URL.createObjectURL(blob); elink.download = filename; elink.click(); URL.revokeObjectURL(elink.href); document.body.removeChild(elink); }
|
https://blog.csdn.net/weixin_43928792/article/details/122881900
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
|
export function download(url, params, filename) { return service .post(url, params, { transformRequest: [ ], headers: { "Content-Type": "application/json;charset=utf-8", }, 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); }); }
|
参考