后端接口返回的是文件流(数据流),前端代码如何实现下载文件流--封装代码
实例代码环境
前端框架:vue3.0
请求插件:axios 1.6.2
export async function downFile(url, params, config) {downloadLoadingInstance = ElLoading.service({ text: '正在下载数据,请稍候', background: 'rgba(0, 0, 0, 0.7)' })service.get(url, {params,headers: { 'Content-Type': 'application/x-www-form-urlencoded' },responseType: 'blob',...config}).then(async (resp) => {const { data } = respconst isLogin = await blobValidate(data)if (isLogin) {var patt = new RegExp('filename=([^;]+\\.[^\\.;]+);*')var contentDisposition = decodeURI(resp.headers['content-disposition'])var result = patt.exec(contentDisposition)var fileName = result[1]fileName = fileName.replace(/\"/g, '')const blob = new Blob([data])saveAs(blob, fileName)} else {const resText = await data.text()const rspObj = JSON.parse(resText)const errMsg = errorCode[rspObj.code] || rspObj.msg || errorCode['default']ElMessage({message: errMsg,type: 'error'})}}).catch(() => {ElMessage({message: '下载文件出现错误,请联系管理员!',type: 'error'})}).finally(() => {downloadLoadingInstance.close()})
}