在请求中需要设置 responseType: blob
javascript
export const requestExport = (api, method, params = {}, config) => {
const apiToken = localStorage.getItem('token');
const data = method === 'GET' ? 'params' : 'data';
let headers = {
'BackServer-Token': `${apiToken}`,
};
if (config?.headers) {
headers = {
...headers,
...config.headers,
};
}
return new Promise((resolve, reject) => {
axios({
...config,
url: baseUrl + api,
method,
[data]: params,
headers,
responseType: 'blob'
})
.then(res => {
if (res.status === 200) {
resolve(res)
}
})
.catch(error => {
ElMessage({
message: '服务器繁忙请稍后重试!',
type: 'error'
})
reject(error);
});
});
};
并且核心在于函数:
javascript
export const download = (fileName, res) => {
const blob = new Blob([res.data],{type: 'application/vnd.ms-excel'});
if ("download" in document.createElement("a")) {
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);
}
}
在页面中发送请求:
在 element 的表格组件中对选中的行进行导出
javascript
const exportTags = async () => {
if (selectId.length < 1) {
ElMessage.error('至少选择一个标签!')
} else {
await exportTag({'tag_ids': selectId}).then(res => {
download('标签列表.xlsx', res)
selectId = []
}, (err) => {
ElMessage.error('导出失败!')
})
}
}