Vue 打包下載圖片


1、 npm安裝依賴

 
         
 //jszip是一個用於創建、讀取和編輯.zip文件的JavaScript庫
https://stuk.github.io/jszip/

npm install jszip
https://www.npmjs.com/package/file-saver npm install file-saver

2、在所需頁面中引入

import JSZip from "jszip";
import FileSaver from "file-saver";

3、打包

arrImages:[{fileUrl:'圖片地址',renameFileName:'圖片名'}]
filename:'打包名'

this
.filesToRar(arrImages, "相冊");

 

    filesToRar(arrImages, filename) {
      let _this = this;
      let zip = new JSZip();
      let cache = {};
      let promises = [];
      let times = 1;
      var setIme = setInterval(() => {
        times++;
        console.log(times);
      }, 1000);

      for (let item of arrImages) {
        const promise = _this.getImgArrayBuffer(item.fileUrl).then(data => {
          // 下載文件, 並存成ArrayBuffer對象(blob)
          zip.file(item.renameFileName, data, { binary: true }); // 逐個添加文件
          cache[item.renameFileName] = data;
        });
        promises.push(promise);
      }
      Promise.all(promises)
        .then(() => {
          zip.generateAsync({ type: "blob" }).then(content => {
            // 生成二進制流
            FileSaver.saveAs(content, filename); // 利用file-saver保存文件  自定義文件名
            this.$notify.close();
            this.$notify({
              message: "壓縮完成"
            });
            window.clearInterval(setIme);
          });
        })
        .catch(res => {
          this.$notify({
              message: "文件壓縮失敗"
            });
        });
    },
    //獲取文件blob
    getImgArrayBuffer(url) {
      let _this = this;
      return new Promise((resolve, reject) => {
        let xmlhttp = new XMLHttpRequest();
        xmlhttp.open("GET", url, true);
        xmlhttp.responseType = "blob";
        xmlhttp.onload = function() {
          if (this.status == 200) {
            resolve(this.response);
          } else {
            reject(this.status);
          }
        };
        xmlhttp.send();
      });
    },

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM