JavasSript后台返回 csv base64 下载
Posted 努力挣钱的小鑫
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JavasSript后台返回 csv base64 下载相关的知识,希望对你有一定的参考价值。
const exort = async () =>
try
const data = await zhjxDownloadFile(
meta:
user_token: localStorage.getItem(\'user_token\'),
file_name: activeName.value,
image_indexs: activePage.value,
,
);
let uri = \'data:text/csv;base64,\' + data.csv;
const a = document.createElement(\'a\');
a.download = `$activeName.value.replace(\'.pdf\', \'\')-page$activePage.value.csv`;
a.href = uri;
a.click();
ElMessage.success(\'导出成功\');
catch (error)
;
处理后台返回的文件流,base64码实现文件导出功能
借鉴文章:https://blog.csdn.net/developer_qi/article/details/87803950
一、 处理文件流
① 请求接口时,声明responseType: ‘blob‘, 告诉后台需要返回的的报文是文件
export function writeWithHead(params) { return request({ url: window.CONFIG.restIp + ‘/workOrderExcelOutDto/writeWithHead‘, method: ‘post‘, data: params, responseType: ‘blob‘, // 请求的时候必须添加 timeout: 200000 }) }
② 处理后台返回的流数据
......
writeWithHead(params).then(res => { if (res.status === 200) { this.$message({ type: "success", message: ‘导出成功‘ }) const blob = new Blob([res.data]); const fileName = ‘导出文件.xlsx‘;//下载文件名称 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); // 释放URL 对象 document.body.removeChild(elink); } else { this.$message({ type: "error", message: ‘导出失败‘ }); } });
二、 base64码 (原理一样,多一步操作,需要将base64码转换成文件流后在操纵)
......
writeWithHead(params).then(res => { if (res.status === 200) { this.$message({ type: "success", message: ‘导出成功‘ }) this.downloadFileByBase64(res.data,‘导出列表‘)
} else { this.$message({ type: "error", message: ‘导出失败‘ }); } });
dataURLtoBlob (dataurl, filename) {
let arr = dataurl.split(","); let mime = arr[0].match(/:(.*?);/)[1]; let bstr = atob(arr[1]); let n = bstr.length; let u8arr = new Uint8Array(n); while (n--) { u8arr[n] = bstr.charCodeAt(n); } return new Blob([u8arr], { type: mime }); }, downloadFile (url, name = "导出列表") { var a = document.createElement("a"); a.setAttribute("href", url); a.setAttribute("download", name); a.setAttribute("target", "_blank"); let clickEvent = document.createEvent("MouseEvents"); clickEvent.initEvent("click", true, true); a.dispatchEvent(clickEvent); }, downloadFileByBase64 (base64, name) { let myBlob = this.dataURLtoBlob(base64); let myUrl = URL.createObjectURL(myBlob); this.downloadFile(myUrl, name); },
有不足之处,还望大佬多指教
以上是关于JavasSript后台返回 csv base64 下载的主要内容,如果未能解决你的问题,请参考以下文章