vue3 将文件集合下载后导出zip文件

发布时间 2023-09-22 14:17:09作者: 随手笔记

// 注意:文件的url一定是服务器上的地址 如http:xxxx

// 先下载
npm i jszip file-saver

// 封装
import JSZip from 'jszip'
import FileSaver from 'file-saver'
const getFile = (url) => {
  return new Promise((resolve, reject) => {
    // 通过请求获取文件blob格式
    let xmlhttp = new XMLHttpRequest()
    xmlhttp.open('GET', url, true)
    xmlhttp.responseType = 'blob'
    xmlhttp.onload = () => {
      if (xmlhttp.status == 200) {
        resolve(xmlhttp.response)
      } else {
        reject(xmlhttp.status)
      }
    }
    xmlhttp.send()
  })
}
export const downloadZip = (fileList) => {
  const zip = new JSZip()
  const promiess = []
  fileList.forEach((item) => {
    const reqList = getFile(item.filePath, item.fileName).then((res) => {
      zip.file(item.fileName, res, { binary: true })
    })
    promiess.push(reqList)
  })
  Promise.all(promiess).then(() => {
    zip
      .generateAsync({ type: 'blob' })
      .then((content) => {
        FileSaver.saveAs(content, '附件') // content 内容  附件:zip文件名称
      })
      .catch(() => {
        window.$message.error('文件压缩失败')
      })
  })
}


// 在页面中使用
downloadZip(fileList)