使用JSZip库解压后台返回的Blob格式文件,并回显到element-ui的el-upload组件

有一个报告列表,点击编辑的时候需要回显新建时上传的附件。后台提供了一个下载接口,但是会将所有上传的文件打包为一个压缩的blob。类似这种:

let urlArr = [];
      urlArr = urlArr.concat(this.downLoadUrl.split(";"));
      this.$http
        .downLoadFile({ url: urlArr.join(",") })
        .then(res => {
          const blob = new Blob([res.data]);
          let url = window.URL.createObjectURL(blob);
          let link = document.createElement("a");
          link.style.display = "none";
          link.href = url;
          link.setAttribute("download", "附件.zip");
          document.body.appendChild(link);
          link.click();
        })

我需要把后台打包的文件解压之后回显。需要用到JSZip插件,需要安装一下。

npm install jszip

使用的页面引入。

import JSZip from "jszip";

最后就是先走接口取回数据,然后处理回显。

     let operateFileList = [];
        let urlArr = [];
        urlArr = urlArr.concat(data.fileUrl.split(";"));
        this.$http
          .downLoadFile({ url: urlArr.join(",") })
          .then(res => {
            const blobData = res.data;
            JSZip.loadAsync(blobData).then(zip => {
              const promises = [];
              zip.forEach((relativePath, zipEntry) => {
                promises.push(
                  zipEntry.async("blob").then(contentBlob => {
                    // 创建file对象
                    const file = new File([contentBlob], zipEntry.name, {
                      type: contentBlob.type
                    });
                    operateFileList.push({
                      name: zipEntry.name,
                      raw: file
                    });
                  })
                );
              });
              Promise.all(promises).then(() => {
                this.fileList = operateFileList;
              });
            });
          })

 

posted on 2024-01-18 15:36  hanguahannibk  阅读(228)  评论(0编辑  收藏  举报