export function exportEmployeeList (data) {
return post(`${baseUrl}staff/excel`, data, {
headers: {
'Content-Type': 'application/json'
},
responseType: 'blob'
})
}
exportEmployeeList({
mainDepartmentIds: mainDepartmentId,
keyWords: this.searchData.name
}).then(res => {
const blob = new Blob([res], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
const downloadElement = document.createElement('a')
const href = window.URL.createObjectURL(blob)
downloadElement.href = href
downloadElement.download = decodeURI('员工列表') // 下载后文件名
document.body.appendChild(downloadElement)
downloadElement.click() // 点击下载
document.body.removeChild(downloadElement) // 下载完成移除元素
window.URL.revokeObjectURL(href) // 释放掉blob对象
})
...
const blob = new Blob([res.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
const downloadElement = document.createElement('a')
const href = window.URL.createObjectURL(blob)
const contentDisposition = res.headers['content-disposition'].split('=')[1] || ''
const iconv = require('iconv-lite')
iconv.skipDecodeWarning = true
const fileName = iconv.decode(contentDisposition, 'utf-8')
downloadElement.href = href
downloadElement.download = decodeURI(fileName.split('.')[0])
...
- 后端返回的数据流时,前端和后端约定好返回的数据格式
- 前端同步设置responseType为blob
- 转换blob时配置type值如下即可
const blob = new Blob([res], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
- 文件名编码格式需同后台返回一致
浏览器兼容问题记录-safari浏览器兼容
const blob = new Blob([data], { type: 'text/csv' });
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = 'my_file.csv';
link.click();
URL.revokeObjectURL(url);
fetch(data?.url)
.then(response => response.blob())
.then((blob) => {
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
const fileNameList = data?.url?.split('?')[0].split('/');
link.download = decodeURIComponent(fileNameList[fileNameList.length - 1]);
link.click();
URL.revokeObjectURL(url);
});