后台返回文件流格式,前端进行下载对应文件
//接口
export function fileDataDownloadIO(params) {
return request({
url: '/fileData/downloadIO',
method: 'GET',
params,
responseType: 'blob', //设置响应格式
headers: {
'Content-Type': 'application/x-www-form-urlencoded', //设置请求头,根据后台需要格式
}
})
}
//下载按钮
<el-button type="primary" class="addBtn" @click="addItem">下载所选</el-button >
后台返回文件流
通过blob转换获取需要的data和改变文件名
//调用方法
addItem() {
let res = await fileDataDownloadIO({ id: downloadSelection });
const blob = new Blob([res.data], { type: res.data.type });
console.log("下载文件的值,", res);
const fileName = res.headers["content-disposition"].split(";");
const filename2 = fileName[1].split("=");
const filename3 = decodeURIComponent(filename2[1]);
let downloadElement = document.createElement("a");
let href = window.URL.createObjectURL(blob);
downloadElement.href = href;
downloadElement.download = filename3;
console.log("filename3", filename3);
document.body.appendChild(downloadElement);
downloadElement.click();
document.body.removeChild(downloadElement); //移除元素;防止连续点击创建多个a标签
window.URL.revokeObjectURL(href);
},
下载成功显示
遇到问题
1.如果出现类似问题
This XML file does not appear to have any style information associated with it. The document tree is shown below.
原因:后台返回type格式有误
解决方法:叫后台改
2.下载的文件是这样的
原因:因为没设置文件名
解决方法:加上文件名就行,在返回的header里面,如果没有的话叫后台给