第一步:前端导出设置responseType:‘blob‘
正常情况下,我们导出功能的请求需要在请求头中添加responseType:‘blob,已保证拿到正确的文本流,然后通过后端返回文本流,我们前端生成a标签,借以实现导出文本!
接口如下:
// 导出
export function zjExportUpdata(id) {
return request({
url: `/infomgr/attach/batch-download?relIds=${
id}`,
method: 'get',
responseType: 'blob'
})
}
返参处理
// 导出
async downloadFile(date) {
let {
data, code } = await zjExportUpdata(date);
if(data.code){
this.$message.error('暂无附件可导出')
} else {
let link = document.createElement("a");
link.style.display = "none";
let blob = new Blob([data], {
type: "application/vnd.ms-excel;charset=utf-8",
});
link.href = URL.createObjectURL(blob);
link.download = localStorage.getItem("fileName");
// 获取文件名
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
},
第二步:获取导出的文件名
一般的导出文件的名称都是后端动态返回的,当然也有前端固定写死的!
1:后端返回
一般后端返回,他会把文本名称放在请求头里的content-disposition,我们可以在response返回中获取,然后可以通过localStorage存起来
async response => {
const disposition = response.headers['content-disposition'];
if