vue项目处理数据流文件下载

1,019 阅读1分钟
this.axios({
        method: method,
        url:url,
        headers: {
          // 'Content-Type': 'application/json;charset=UTF-8'
        },
        responseType: 'blob',
        data: {}//请求参数
      })
        .then(res => {
          const isEXCLE =
            res.headers['content-type'] === 'multipart/form-data;charset=utf-8'
          if (!isEXCLE) {
          //这个判断是如果接口报错,需要提示错误信息
            let reader = new FileReader()
            reader.onload = e =>
              this.$message({
                type: 'warning',
                message: JSON.parse(e.target.result).message
              })
            reader.readAsText(res.data)
          } else {
          //首先需要打印res,看res返回过来的参数,其中打印的结果是浏览器只能访问以下默认的 响应头,而我需要让浏览器能访问到其他的响应头的话, 需要在服务器上设置 Access-Control-Expose-Headers:content-disposition(后端设置),然后就可以获取到我需要的content-disposition的内容,以此来做下面的判断
            let disposition = res.headers['content-disposition']
            let fileName = decodeURI(
              disposition.substring(
                disposition.indexOf('filename=') + 9,
                disposition.length
              )
            )
            let blob = new Blob([res.data], {
              type:
                'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8'
            })
            let link = document.createElement('a')
            link.href = window.URL.createObjectURL(blob)
            link.download = fileName
            link.click()
            link.remove()
            this.$message({
              type: 'success',
              message: 'success'
            })
          }
        })
        .catch(err => {
        })
        
        参考地址:https://segmentfault.com/a/1190000009125333
        https://www.jb51.net/article/161049.htm
        http://www.imooc.com/wenda/detail/550199
        https://www.imooc.com/wenda/detail/409954
        
        
        
    后端以文件流形式返回图片,处理图片显示
        ``` 
    getfileLogo() {
      this.axios({
        method: method,
        url:url,
        responseType: 'arraybuffer'
      })
        .then(res => {
          let blob = new Blob([res.data], {
            type: 'image/png,image/jpg'
          })
          const url = window.URL.createObjectURL(blob)
          this.filenameLogo = url
        })
        .catch(err => {})
    },
    
    参考地址:https://www.cnblogs.com/steamed-twisted-roll/p/11821148.html