赞
踩
Blob
解析并下载arraybuffer
或 blob
(设置响应类型)
responseType: 'arraybuffer'
或 responseType: 'blob'
axios
为例(有可能你的项目对 axios 进行了二次封装, 你需要找到 options 来配置 )
get
请求写法
axios.get(url, {
params: form,
responseType: 'arraybuffer'
// responseType: 'blob'
})
post
请求写法
axios.post(url, params, {
responseType: 'arraybuffer'
// responseType: 'blob'
})
Blob
对象解析并下载
文件名和类型的信息存放在 content-disposition
和 content-type
decodeURIComponent
解码axios
为例处理, res
为请求成功后后端返回数据的参数let filename = decodeURIComponent( res.headers['content-disposition'].split(';')[1].split('=')[1] ) // let filename = '导出表格.xlsx' // 可以, 但不建议直接写文件名 let fileType = decodeURIComponent(res.headers['content-type']) let blob = new Blob([res.data], { type: fileType // type: 'application/vnd.ms-excel' // 特殊情况下直接写文件的MIME类型 }) let url = window.URL.createObjectURL(blob) // 创建一个临时的url指向blob对象 // 创建url之后可以模拟对此文件对象的一系列操作,例如:预览、下载 let a = document.createElement('a') a.href = url a.download = filename // 下载 a.click() // 释放这个临时的对象url window.URL.revokeObjectURL(url)
注意
1. filename 可以直接赋值一个字符串包含文件后缀名, 例如: ('导出表格.xlsx'), 但建议从响应头取
2. new Blob() 的第一个参数为一个数据序列,可以是任意格式的值,例如,任意数量的字符串,Blobs 以及 ArrayBuffers , 不一定是 [res.data] , 也可能是 [res.body] 或其它, 具体根据后端的返回来写
3. new Blob() 的第二个参数用于指定将要放入 Blob 中的数据的类型 (MIME) , 大多数情况从响应头取, 但是后端返回 ( content-type: application/octet-stream 是默认的未知的类型, 除非你知道具体是什么类型,否则解析不出来 ) 的时候需要自己手动设置 MIME 类型。 例如: Excel 表需设置成 { type: 'application/vnd.ms-excel' }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。