vue axios实现下载文件及responseType:blob注意事项

需要使用axios和js-file-download组件

npm install js-file-download --save
npm install axios --save
import fileDownload from 'fileDownload'; // 引入fileDownload
import axios from 'axios'; // 引入axios 

axios({
	method: 'get',
    url: 'xxxxxxx',
    responseType: 'blob'
}).then(res => {
    if(res.status == 200){
      // res.headers['content-disposition'].substring(20)表示从响应头中获取文件名
      fileDownload(res.data,res.headers['content-disposition'].substring(20));
    }else { // 下载文件失败,解析json格式信息
      let that = this;
      var fileReader = new FileReader();
      fileReader.readAsText(res.data); // 按字节读取文件内容,结果为文件的二进制串
      fileReader.onload = ()=>{
          that.$notify.error(fileReader.result);
      }
    } 
})

注意事项:responseType:blob表示服务器返回的响应类型是二进制流,一般用于文件、视频下载等场景。正常情况下后端返回二进制数据,当后端服务器出错时,往往会以json形式返回错误信息,例如{"code":500,"msg":"未知异常"}。因为设置了blob类型,axios会强制把数据转为blob,导致json格式的响应没办法正常解析,需要使用FileReader对象来处理,FileReader是一种异步读取文件机制。FileReader提供了如下方法,大家根据需要自行选择。

  • readAsArrayBuffer(file):按字节读取文件内容,结果用ArrayBuffer对象表示

  • readAsBinaryString(file):按字节读取文件内容,结果为文件的二进制串

  • readAsDataURL(file):读取文件内容,结果用data:url的字符串形式表示

  • readAsText(file,encoding):按字符读取文件内容,结果用字符串形式表示

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
根据引用\[1\]和引用\[2\]的内容,如果你想在Vue中使用axios设置responseType,你可以尝试注释掉引入mockjs的代码,并在源码中的dist/mock.js文件的约8683行处添加一行代码this.custom.xhr.responseType = this.responseType。这样做可以解决mockjs拦截响应设置responseType无效的问题。 另外,根据引用\[3\]的内容,如果你在上传音频文件时遇到问题,浏览器可能会返回一串乱码字符串而不是Blob类型。你可以尝试在axios请求中添加responseType: "blob"来指定返回的数据类型为Blob文件流。如果这个方法仍然无效,你可以参考一位大佬的博客文章,他提供了关于vue axios设置responseType:'blob'无效的问题的解决方案。 #### 引用[.reference_title] - *1* *3* [vue axios(获取文件流乱码)设置返回值类型responseType:‘blob‘无效](https://blog.csdn.net/sinat_36359516/article/details/119641566)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [vue axios(下载文件流)设置返回值类型responseType:'blob'无效的问题](https://blog.csdn.net/weixin_42142057/article/details/97655591)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

宝藏程序员

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值