vue前端处理下载流的几种方式

1、使用blob类型

	downloadFile(){
        this.loading = true
        this.api.后端接口方法名({param}, resp=>{
          this.loading = false
          if (resp.headers['content-type'].includes('octet-stream')) {
            const blob = new Blob([resp.data], { type: 'application/octet-stream;charset=UTF-8' }) //可根据不同的文件格式设置不同的参数
            const fileName = decodeURI(resp.headers['content-disposition'].replaceAll('"', '').split('=')[1])
            if (navigator.msSaveBlob) {
              // deal with IE 11, data是第一步toBlob的结果值
              window.navigator.msSaveOrOpenBlob(blob, fileName)
            } else {
              const url = URL.createObjectURL(blob)
              const link = document.createElement('a')
              link.setAttribute('href', url)
              link.style.visibility = 'hidden'
              link.download = fileName // 给下载的文件命名
              document.body.appendChild(link)
              link.click()
              document.body.removeChild(link)
            }
          } else {
            let _this = this
            const blob = new Blob([resp.data], { type: 'text/plain;charset=UTF-8' })
            var reader = new FileReader();
            reader.readAsText(blob, 'utf-8');
            reader.onload = function (e) {
              _this.$message.error(reader.result)
            }
          }
        })
      },

2、浏览器自身行为window.open(URL)

优点:简单操作
缺点:没办法携带token

你可能感兴趣的:(VUE,前端,vue.js,javascript)