Vue前端处理后端返回的文件流乱码,导出Excel
export function exportDataList () {return axios.get('/export?tableName=list', { responseType: 'blob' })}exportData() {exportDataList().then((res) => {this.downloadfile(res)}).catch((err) => {con
·
export function exportDataList () {
return axios.get('/export?tableName=list', { responseType: 'blob' })
}
exportData() {
exportDataList().then((res) => {
this.downloadfile(res)
}).catch((err) => {
console.log('错误信息', err)
this.$message.error('下载错误:获取文件流错误')
})
},
downloadfile (res) {
var blob = new Blob([res.data], { type: 'application/octet-stream;charset=UTF-8'})
var contentDisposition = res.headers['content-disposition']
var patt = new RegExp('filename=([^;]+\\.[^\\.;]+);*')
var result = patt.exec(contentDisposition)
var filename = result[1]
var downloadElement = document.createElement('a')
var href = window.URL.createObjectURL(blob) // 创建下载的链接
var reg = /^["](.*)["]$/g
downloadElement.style.display = 'none'
downloadElement.href = href
downloadElement.download = decodeURI(filename.replace(reg, '$1')) // 下载后文件名
document.body.appendChild(downloadElement)
downloadElement.click() // 点击下载
document.body.removeChild(downloadElement) // 下载完成移除元素
window.URL.revokeObjectURL(href)
},
axios.get('/export?tableName=list', { responseType: 'blob' }),一定要记得加{ responseType: 'blob' },否则前端接收到的就是乱码!
更多推荐
已为社区贡献1条内容
所有评论(0)