vue实现接受后台文件流转文件并下载

接受到的文件流是这样的

 

1,首先在请求时加上  responseType:'blob'

 request({
    url: "url",
    method: "get",
    responseType:'blob',  //加上这一行
    params:params
 })

 

 

2,在获取到返回来的文件流后进行处理

 

//传的参数为图片
downloadImage({file_url:imgUrl}).then( res => {
       //加上{type:"application/octet-stream;"}
       let blob = new Blob([res],{type:"application/octet-stream;"})
       const url = window.URL.createObjectURL(blob);
       const link = document.createElement('a');
       link.href = url;
       //拆分图片地址保留文件名称及格式
       link.setAttribute('download',this.splitStr(imgUrl));
       document.body.appendChild(link);
       link.click();
})

//只保留地址信息最后的文件名称及格式
splitStr(str){
    return str.split('/')[str.split('/').length - 1]
},

 

  

 

3,如果是用的element-ui的图片预览下载,在功能栏位置增加下载按钮并实现下载,如下

html部分

<el-image
        @click="clickImage(imgUrl)"
        class="color-squre"
        :src="imgUrl"
        :preview-src-list="[imgUrl]"
        fit="cover">
      <div slot="error" class="image-slot-dvi">
           无图片
     </div>
</el-image>

  

js部分

//预览图添加下载按钮
    clickImage(img){
      this.$nextTick(() => {
        let wrapper = document.getElementsByClassName(
        'el-image-viewer__actions__inner'
        )
        //下载图标
        let downImg = document.createElement('i')
        downImg.setAttribute('class', 'el-icon-download')
        wrapper[0].appendChild(downImg)
        if (wrapper.length > 0) {
        this.wrapperElem = wrapper[0]
        //调用下载图片事件
        this.downLoadFile()
        }
      })
    },
    downLoadFile() {
      this.wrapperElem.addEventListener('click', (e) => {
        let className = e.target.className
        if (className === 'el-icon-download') {
          let imgUrl = document.getElementsByClassName(
          'el-image-viewer__canvas'
          )[0].children[0].src
          //下载接口
          downloadImage({file_url:imgUrl}).then( res => {
            let blob = new Blob([res],{type:"application/octet-stream;"})
            const url = window.URL.createObjectURL(blob);
            const link = document.createElement('a');
            link.href = url;
            link.setAttribute('download',this.splitStr(imgUrl));
            document.body.appendChild(link);
            link.click();
          })
        }
      })
},

  

 

posted @ 2023-07-06 09:48  江郎才尽吕小布  阅读(4193)  评论(0编辑  收藏  举报