在开发中,axios.post下载文件 需要配置可选参数:
{ responseType: 'blob' }
一开始是这样写的:
axios.post('http://127.0.0.1:8080/download',{ responseType: 'blob' })
死活不对,搜索了好多文章,都是这样写的:
xxxx.post('http://127.0.0.1:8080/download',{ responseType: 'blob' })
查看axios.post 相关文档发发现axios.post 的参数应该是:
AxiosInstance.post<any>(url: string, data?: any, config?: AxiosRequestConfig): AxiosPromise<any>
改成:
axios.post('http://127.0.0.1:8080/download',{},{ responseType: 'blob' })
搞定,其实就是参数位置没写对,按搜索到的文章为什么那样写?是他们写错了?其实不然!是因为文章作者用的可能是对axios进行了一次封装,所以在面向搜索引擎编程的时候千万不要直接就拷贝别人的代码,还得自己过过脑子。
完整代码:
const res = await axios.post('http://127.0.0.1:8080/download', {}, { responseType: 'blob' })
const blob = new Blob([res.data])
// window.URL.createObjectURL(blob)
const elink = document.createElement('a')
elink.download = 'fileName.zip'
elink.style.display = 'none'
elink.href = URL.createObjectURL(blob)
document.body.appendChild(elink)
elink.click()
URL.revokeObjectURL(elink.href)
document.body.removeChild(elink)











网友评论