简体   繁体   中英

How to download multiple image files in .zip folder using JSZip in Vue.js

I am using Vue.js in a current project of mine and in that I need a feature, which will help any user to download pics that are available in the gallery.

There is an option that the user can select multiple images by clicking on the checkbox besides every image and to download the user needs to click a button to download all the pics that the user may have selected. The download will compress all the selected images to a zip folder and then the downloading stars and the user gets a final zip folder of all of the images that were selected.

To deliver this feature I have tried many Vue.js libraries but only JSZip was able to work for some extend. JSZip packed the images to a .zip and then downloads the zip folder but the images that are being packed, the type:"image/?" is also present but when one will open the file to see the image , then it gives an error of:

not an image of the defined type

in the image viewer. Here is the sample of the code that I have used:

export default {
  methods: {
    download_btn() {
      var zip = new JSZip()
      var img = zip.folder("images")
      for (i = 0; i < this.image.length; i++) {
        img.file("img.png", this.image[i].imageurl)
      }
      zip.generateAsync({
        type: "blob"
      }).then(function(content) {
        saveAs(content, "img_archive.zip")
      })
    }
  }
}

This code only saves one picture in the zip folder and also you can't open the image file.

According to https://stuk.github.io/jszip/documentation/api_jszip/file_data.html the file method expects the image data as the second param to the call. It looks like you are passing the url of the image instead of the actual image bytes. If you refer to the docs you will see they retrieve the image via an ajax call.

To save more than one image, try using the number in the filename. And you'll have to use the image data, not the url, just like Deadron said.

In the docs they use xhr within a promise, see https://stuk.github.io/jszip/documentation/examples/downloader.html

Instead of:

for (i = 0; i < this.image.length; i++) {
    img.file("img.png", this.image[i].imageurl)
}

Try:

for (i = 0; i < this.image.length; i++) {
    img.file("img" + i + ".png", /* image data */)
}

Have a look at this one. Maybe it will help.

https://jsfiddle.net/jaitsujin/zrdgsjht/

You can manage zip folder structure by modifying this line

filename = filename.replace(/[\/\*\|\:\<\>\?\"\\]/gi, '').replace("httpsi.imgur.com","");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM