vue (前端将文件下载为.zip格式)

一. 安装依赖包

npm install jszip
npm install file-saver

二. 在需要下载 .zip 格式的页面导入下载的依赖包

import JSZip from 'jszip'
import FileSaver from 'file-saver'

三. 在点击下载按钮的事件中对下载数据进行处理
      Html点击事件

<span class="iconfont iconfont-add-down yj_downloa" @click="handleBatchDownload(item)" />

        click点击事件中数据的处理

handleBatchDownload(item) {
      const dataUrl = []
      item.lval.forEach(element => {
        if (element.sourceType === 'tp') {  // 试卷需要自己下载word
          document.querySelector('.exportBoxPaper').innerHTML = ''

          this.getTestPaperInfo(element.sourceId, element.name)  // 这边是去下载试卷的word
        } else {
          var newUrl = ''
          if (element.val && element.sourceType !== 'tp') {
            newUrl = element.val.split('downloadFile')[1] + '/' + element.name + '.' + element.format
          }

          dataUrl.push(newUrl)
        }
      })

      // const zip = new JSZip()	// 创建一个JSZip实例
      // const cache = {}
      dataUrl.forEach(item => {
        const promise = this.getFile(item).then(data => { // 下载文件, 并存成ArrayBuffer对象
          const arr_name = item.split('/') // stringObject.split 将字符串分割成字符串数组
          const file_name = arr_name[arr_name.length - 1] // 获取文件名(数组最后一项)
          this.zip.file(file_name, data, { binary: true }) // 逐个添加文件
          this.cache[file_name] = data
        })
        this.promises.push(promise) // 将要下载的文件流都加入this.promises数组中
      })
      console.log(' this.zip: ', this.zip)
      Promise.all(this.promises).then(() => {
        this.zip.generateAsync({ type: 'blob' }).then(content => { // 生成二进制流
          // 利用file-saver保存文件 _this.fileTableTitle是我压缩包名字
          FileSaver.saveAs(content, item.name + '.zip')
        })
      })
    },

     在下载的时候需要走后端的接口

 getFile(url) {
      return new Promise((resolve, reject) => {
        loadFile(url).then(data => {  // 形成一个下载流
          resolve(data.data)
          // console.log(data.data)
        }).catch(error => {
          // 在此写入你的错误处理
          // 可以在此处处理promise.all失败的情况,放在methods里主要也是为了方便对data里的变量处理
          reject(error.toString())
        })
      })
  }

总结

下载下来的时候,别忘记查看一下压缩包中每个文件后缀时候存在,像我第一次下载的话忘记加上每个文件的后缀,然后想去打开文件是识别不了是什么类型的文件,而且压缩包中文件前面的小图标也不显示

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值