在vue项目中,使用文件下载的时候,后端返回的二进制数据流,需要在axios里面设置responseType:blob,否则会打开无效。

1、当后端接口稳定返回的不是二进制数据流的话。那么设置了 responseType:blob。 也会把后端的返回值解析成为 blob {}
如下图
在这里插入图片描述

解决方法:

      const _this = this
      this.GET_DOWNLOAD_FILE(params).then(response => {
        const fileReader = new FileReader()
        fileReader.onload = function() {
          try {
          	// this.result  = 字符串类型的 response 
            const fileResult = JSON.parse(this.result)  
            //  如果接口返回的数据,非二进制的话。可以根据response做出响应的判断。
            if (fileResult.xxx) { //想干啥你干啥 } 
            //  ps:JSON.parse()是Javascript中一个常用的 JSON 转换方法,JSON.parse()可以把JSON规则的字符串转换为JSONObject 反之就会报错。
            //  如果接口内容为二进制数据。那么JSON.parse解析失败, 抛出异常来到catch进行执行下载操作
            }
          } catch (err) {
            // 当前构造函数内的this是指向它的实例对象的。所以在外层声明了一个this用于指向全局
            _this.saveFileToLocal(response, fileName) // 调用下载文件的方法
          }
        }
        fileReader.readAsText(response)
      }).catch(e => {
		 console.log('接口报错要执行的代码')
      })
文件下载方法 兼容 IE
    saveFileToLocal(res, fileName) {
      // 兼容 IE
      if (window.navigator && window.navigator.msSaveOrOpenBlob) {
        window.navigator.msSaveOrOpenBlob(new Blob([res]), fileName)
      } else {
        // 非IE 浏览器
        const url = window.URL.createObjectURL(new Blob([res], { type: res.type }))
        const link = document.createElement('a')
        link.href = url
        link.setAttribute('download', `${fileName}`)
        document.body.appendChild(link)
        link.click()
      }
    },

2、什么是 FileReader()

FileReader 对象允许Web应用程序异步读取存储在用户计算机上的文件(或原始数据缓冲区)的内容,使用 FileBlob 对象指定要读取的文件或数据。

属性:
  • FileReader.error 表示在读取文件时发生的错误
  • FileReader.readyState
  • FilerReader.result 读取到的结果 (上面用到的)

个人总结: 在文件没有下载之前,通过fileReader对象,访问到当前存储在用户计算机的内容(this.result)利用 try catch 进行区分 result 的结果是否可以下载。

PS:欢迎指出不足之处

你唯一能把握的,是变成更好的自己

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐