后台返回格式为二进制流进行文件的下载
结合项目中
封装get请求携带token,进行接收二进制流
export function getHeader() { const token = getToken(); if (token) { return { headers: { "Authorization": "Bearer " + token, } } } return { headers: {} } } export function getHeader() { const token = getToken(); if (token) { return { headers: { "Authorization": "Bearer " + token, } } } return { headers: {} } }
具体文件使用
TaskManageServer.js文件:
export const dataExport2 = (vueObject, dataIdList) => getDataRaw(vueObject,dataExport1(dataIdList)) export const dataExport1 = (dataIdList)=> { var tmp =""; for (let i = 0; i <dataIdList.length; i++) { tmp+= dataIdList[i]+"," } tmp = tmp.substr(0,tmp.length-1) var url = getUrl('image/export/' + tmp); return url; }
对应html文件具体使用:
import { dataExport1, dataExport2 } from './TaskManageServer' const response = await dataExport2(this, this.dataIdList); let blob = new Blob([response.data], { //下载的文件类型; type: 'application/zip' }) // let fileName = Date.parse(new Date()) + '.zip'(修改下载的文件名) if (window.navigator.msSaveOrOpenBlob) { // navigator.msSaveBlob(blob, fileName) navigator.msSaveBlob(blob) } else { var link = document.createElement('a') link.href = window.URL.createObjectURL(blob) // link.download = fileName link.click() window.URL.revokeObjectURL(link.href) //释放内存 }
即可实现下载二进制流文件。
vue下载保存二进制文件
方法封装:util.js
/** * 把二进制文件保存到本地 */ export function exportFile(file, name) { let url = window.URL.createObjectURL(new Blob([file])); let link = document.createElement("a"); link.style.display = "none"; link.href = url; link.setAttribute("download", name); document.body.appendChild(link); link.click(); document.body.removeChild(link); // 下载完成移除元素 window.URL.revokeObjectURL(url); // 释放掉blob对象 }
请求接口
在请求头加responseType: "arraybuffer"
export function demoApi(data) { return http({ url: "/path/export", method: "post", responseType: "arraybuffer", data, }); }
方法调用
demoApi(data).then(res=>{ if(res.staus==200){ let fileName = ""; let contentDisposition = res.headers["content-disposition"]; if (contentDisposition) { fileName = window.decodeURI( res.headers["content-disposition"].split("=")[1], "UTF-8" );//取文件名 } exportFile(res.data, fileName); } })
以上为个人经验,希望能给大家一个参考,也希望大家多多支持阿兔在线工具。