导语
本篇文章介绍vue如何实现后台接口返回二进制流实现文件下载
注意axios的responseType: 'blob'为接口响应数据的类型,当res.data.type === 'application/json'时,后台接口返回json数据为下载接口异常的报错信息
1、JS代码实现
下面为自己封装的方法export.js,只需要点击按钮时调用此方法进行对应传参即可
import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
export function exportFileFn(url, params = {}) {
Message({
message: '文件导出下载中',
type: 'info',
duration: 3 * 1000
})
const baseUrl = process.env.NODE_ENV === 'production' ? '' : '/api'
return new Promise((resolve, reject) => {
const fileName = '文件名'
axios({
url: baseUrl + url,
method: 'post',
data: params,
responseType: 'blob'
})
.then((res) => {
if (res.data.type === 'application/json') {
const reader = new FileReader()
reader.readAsText(res.data, 'utf-8')
reader.onload = () => {
const json = JSON.parse(reader.result)
Message({
message: json.message || '导出文件失败,请稍后重试',
type: 'error',
duration: 3 * 1000
})
return reject()
}
} else {
const blob = new Blob([res.data], {
type: 'application/vnd.ms-excel;charset=utf-8'
}) // res就是接口返回的文件流了
const objectUrl = URL.createObjectURL(blob)
const elink = document.createElement('a')
elink.download = `${fileName}.xlsx`
elink.style.display = 'none'
elink.href = objectUrl
document.body.appendChild(elink)
elink.click()
URL.revokeObjectURL(elink.href) // 释放URL 对象
document.body.removeChild(elink)
Message({
message: '文件导出成功',
type: 'success',
duration: 3 * 1000
})
return resolve()
}
})
.catch(function() {
Message({
message: '导出异常,请稍后重试',
type: 'error',
duration: 3 * 1000
})
})
})
}
网友评论