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):按字符读取文件内容,结果用字符串形式表示

猜你喜欢

转载自blog.csdn.net/weixin_46205984/article/details/132563160