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

// 注意:文件的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)
posted @   Life_countdown  阅读(424)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示