一、如何接收后端的文件流数据并实现点击下载功能
后端返回一个Excel格式的数据,然后前端通过接口接收到之后,点击可以直接下载到本地,里面返回后端的数据。
示例:
二、使用步骤
1.首先在调用后端接口的时候保存一个blob类型的数据。
代码如下(示例):
//这个是vue3单独封装的格式。也可以使用第二种方式:
//下载模板
export function downloadTem(params){
return request({
url:`/uums/drp/report/template`,
method:'get',
params,
responseType: 'blob',
})
}
//第二种格式:如何需要携带token这个需要单独加入,不需要可以删除headers
import axios from 'axios'
axios.request({
method:'GET',
url:'/uums/drp/report/template',
responseType: "blob",
headers:{
'Authorization' = 'Bearer ' + token(需要自己获取的token值)
}
})
2.前端处理一下数据格式就可以了
注意一点:接收的时候要根据后端返回的格式来判断,我们这里接收的是Excel格式的文件,所以使用了这段代码:
let blob = new Blob([res], {type: "application/vnd.ms-excel"});
,这个type
根据自己情况而定。另外可能接口返回的数据在res.data
中,也可能在res
中,这个也根据接口返回数据判断。
代码如下(示例):
//dom操作
<el-button type="success" plain icon="Download" @click="handleDownload($event)">下载模板</el-button>
//vue3中绑定方法
//下载模板
function handleDownload(e){
e.stopPropagation();
downloadTem().then((res) => {
const link = document.createElement("a");
let blob = new Blob([res], {type: "application/vnd.ms-excel"});
link.style.display = "none";
link.href = URL.createObjectURL(blob);
link.download = '模板下载.xlsx';
document.body.appendChild(link);
link.click();
})
}