vue前端根据url批量下载图片

安装依赖

npm install jszip
npm install file-saver

代码
// import
import JSZip from'jszip'
import FileSaver from'file-saver'

// html
<el-button type="primary" :loading="download" @click="down">批量下载</el-button>
<span v-if="download">{{ title }}:{{ ok }} / {{ all }}</span>

// data
data() {
	return {
	  imgList: [],
	  download: false,
      ok: 0,
      all: '',
      title: '正在加载压缩文件',
	}
}

// methods
down() {
  this.all = this.imgList.length 
  this.download = true
  this.Download(this.imgList)
},

getImgListBuffer(url){
  return new Promise((resolve, reject) => {
    let xmlhttp = new XMLHttpRequest()
    xmlhttp.open("GET", '/static' + url, true)
    xmlhttp.responseType = "blob"
    xmlhttp.onload = function () {
      if (this.status == 200) {
        resolve(this.response)
      }else{
        resolve(this.response)
      }
    }
    xmlhttp.send();
  })
},

Download(imgDataUrl){
  let zip = new JSZip()
  let cache = {}
  let promises = []
  for (let item of imgDataUrl) {
    const i = item.slice(25)
    const promise= this.getImgListBuffer(i).then(data => {
      zip.file(item, data, { binary: true })
      cache[item] = data
      this.ok++ // 记录加载图片数
    });
    promises.push(promise)
  }
  Promise.all(promises).then(() => {
    this.title = '正在压缩'
    zip.generateAsync({ type: "blob" }).then(content => {
      FileSaver.saveAs(content, this.value) // 自定义文件名
      this.$message.success('压缩完成')
      this.download = false
      this.ok = 0
    });
  }).catch(res=>{
    this.$message.error('文件压缩失败')
    this.download = false
    this.ok = 0
  })
},

版权声明:本文为JKC_HOWL原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。