文件批量下载为压缩包时遇到同名文件会被忽略的问题(前端)

497 阅读1分钟

前端解决办法:在下载方法中遍历每个文件,当文件名重复时重新命名

代码:

1、图片文件下载方法(base64)

//将图片类型文件转化为base64
image2Base64(img) {
      const canvas = document.createElement('canvas')
      canvas.width = img.width
      canvas.height = img.height
      const ctx = canvas.getContext('2d')
      ctx.drawImage(img, 0, 0, img.width, img.height)
      const dataURL = canvas.toDataURL('image/png')
      return dataURL
    }
    
  getBase64Image(url) {
      return new Promise((resolve, reject) => {
        var base64 = ''
        var img = new Image()
        img.setAttribute('crossOrigin', 'Anonymous')
        img.onload = () => {
          base64 = this.image2Base64(img)
          resolve(base64.split(',')[1])
        }
        img.onerror = () => reject('图片加载失败')
        img.src = url + '?=' + Math.random()
      })
    }
  

2.非图片文件下载方法(文件流)

//获取文件流数据
    getFileArrayBuffer(url) {
      const newUrl = url + '?' + Math.random()
      return new Promise((resolve, reject) => {
        fetch(newUrl, {
          method: 'GET',
          responseType: 'blob'
        }).then(response => {
          return response.blob()
        }).then(data => {
          resolve(data)
        }).catch(error => {
          reject('获取文件流数据失败,请重试')
        })
      })
    },

3、重名文件名处理

 //获取文件名
    getFileName(fileName) {
      const fileArr = fileName.split('.')
      console.log(fileArr)
      let newFileName = ''
      for (let i = 0; i < fileArr.length - 1; i++) {
        newFileName += fileArr[i]
        if (i < fileArr.length - 2) {
          newFileName += '.'
        }
      }
      return newFileName
    },

4、实现批量下载(用到上面的3个方法)

 //fileListContent:要下载的文件列表 fileName:打包为zip的压缩包名字
async teachDownloadAll(fileListContent, fileName) {
      try {
        this.fullscreenLoading = true
        const zip = new JSZip()
        this.fileName = fileName
        const allPicType = ['jpg', 'jpeg', 'png']
        const fileNameList = []
        for (let i = 0; i < fileListContent.length; i++) {
          const item = fileListContent[i]
          const type = item.formatType
          const url = item.ossUrl
          const fileName = this.getFileName(item.attachName)
          let suitName = ''
          const filterData = fileNameList.filter(itm => {
            return itm === fileName
          })
          const nowLength = filterData.length > 0 ? filterData.length : ''
          suitName = fileName + nowLength + '.' + type
          fileNameList.push(fileName)
          if (allPicType.includes(type)) {
            await this.getBase64Image(url).then(res => {
              zip.file(suitName, res, { base64: true }, {
                createFolders: true
              })
            })
          } else {
            await this.getFileArrayBuffer(url).then(res => {
              zip.file(suitName, res, { binary: true }, {
                createFolders: true
              })
            })
          }
        }
      } catch (e) {
        this.$message.error(e)
        this.fullscreenLoading = false
      }
    },

使用:this.teachDownloadAll(fileList, '我的文件')//fileList:从后端获取的文件列表 ,我的文件:压缩包名字