vue 后端返回文件流,前端导出下载
- 配置axios响应拦截器
request.interceptors.response.use((response) => {const res = response.data// 关键代码: 返回的是文件流if (res instanceof Blob) {return response}if (res.code == 200 || res == true) {return res} else {Message.error("连接超时")return Promise.reject(res)}},(error) => {return Promise.reject(error)}
)
- 配置api响应类型
export async function fileExport(params) {return request({url: "/api/file/export",method: "post",data: params,responseType: 'blob', // 配置响应类型headers: {'Content-Type': 'multipart/form-data'}});
}
- 封装解码下载的方法
downloadFile(res) {const fileNames = res.headers["content-disposition"];if (fileNames) {//解码const fileName = decodeURIComponent(fileNames.match(/=(.*)$/)[1]);// 处理返回的文件流const content = res.data;const blob = new Blob([content], {type: "application/octet-stream; charset=utf-8",});if ("download" in document.createElement("a")) {//非IE下载const a = document.createElement("a"); //创建一个a标签a.download = fileName; //指定文件名称a.style.display = "none"; //页面隐藏a.href = URL.createObjectURL(blob); // href用于下载地址document.body.appendChild(a); //插到页面上a.click(); //通过点击触发URL.revokeObjectURL(a.href); //释放URL 对象document.body.removeChild(a); //删掉a标签this.$message.success("下载成功");} else {//IE10 + 下载navigator.msSaveBlob(blob, fileName);this.$message.success("下载成功");}}
},
- 发起下载请求
fileExport({}).then((res) => {// 下载文件this.downloadFile(res);
}).catch((err) => {});
- 后端返回的内容示例
PK-q�cfgfW�d�q�ZCB|��|�*�*h㻆},^�{Va�^K<4�6�N�XQ�dž�9�!P��$��҆�d�c�D�j);��ѝP�g��E�M'O�ʕ����H7L�h���R���G��^�'�{��zސʮB��3�˙��h.�h�W�жF�j娄CQՠ똈���}ιL�U:D�����%އ����,�B���[� �� ;˱� �{N��~��X�p�ykOL��kN�V��ܿBZ~����q�� �ar��{O�PKz��q;�S��M�~s+q�~�>�y�ƹXp`=G��C�q-rh?�ڏ�v��=��_M���5o]���2�`g� ��bb48G_��PKMMr�