在vue2项目中调用接口实现文件下载
接口api写法 写到文件请求的js文件
在请求头中写到token,并且将responseType改为blob
export function exportTemplate(params,token) {
// 需要⽤原⽣axios:
return axios.create({
// 请求路径前缀, 按需填写:
baseURL: "/api",
// 请求超时时间, 0即可
timeout: 0,
})({
url: api.exportTemplate,
method: "post",
params: params,
headers: {
// 携带请求头, 按需填写:
'Authorization': 'Bearer ' + token,
},
// 固定写法, 必填:
responseType: 'blob'
});
}
下载文件的点击下载的方法
uploadTemplate(type) {
let params = {
workId: this.workId,
mode: type,
projectId: this.$store.state.projectId,
};
exportTemplate(params, this.$store.state.token).then((res) => {
const link = document.createElement("a");
// 创建Blob对象, 固定写法
let blob = new Blob([res.data], {type: "application/x-download"});
// 设置元素样式不可⻅
link.style.display = "none";
// 创建下载链接
link.href = URL.createObjectURL(blob);
// 获取⽂件名(后端应确保正确返回⽂件名)
const fileName = `文件名称.xlsx`;
link.setAttribute("download", fileName);
// 加⼊dom树
document.body.appendChild(link);
// ⼿动触发点击事件
link.click();
// 移除之前创建的元素
document.body.removeChild(link);
// 释放Blob对象
window.URL.revokeObjectURL(link.href);
});
},