Saving images from URL using JSzip
Asked Answered
M

3

6

I'm using JSzip to download the html of a div. The div has images inside of it (they're not base64 encoded). Is there a way I can use JSzip to download the files from their image path url? or do they have to be base64 encoded?

My current code is just the basic demo code from the JSzip site (http://stuk.github.io/jszip/)

    var zip = new JSZip();
    var email = $('.Result').html();
    zip.file("test.html", email);
    var content = zip.generate({type:"blob"});
    // see FileSaver.js
    saveAs(content, "example.zip");
Mendive answered 29/10, 2014 at 16:22 Comment(0)
P
11

You might want to try using JSzip-utils it has a call just for downloading images from urls also take a look at the example in JSzip documentation I found it to be very good. You can find working example with code here.

This is just part for downloading that I'm also using to download images from social media using their image source urls.

function urlToPromise(url) {
return new Promise(function(resolve, reject) {
    JSZipUtils.getBinaryContent(url, function (err, data) {
        if(err) {
            reject(err);
        } else {
            resolve(data);
        }
    });
});
}
var zip = new JSZip();
zip.file(filename, urlToPromise(url), {binary:true});
zip.generateAsync({type:"blob"})
.then(function callback(blob) {

    // see FileSaver.js
    saveAs(blob, "example.zip");
});
Pentosan answered 27/2, 2018 at 6:57 Comment(2)
you save me! thanks! i use this code in my chrome extension!Cloudlet
Coincidentally enough I'm also using this on my Chrome Extension. Thank you!Salsbury
B
2

Here is my solution (adapted from here) building within an angular framework (though readily applicable to other frontend approaches):

  1. NOTE: this only works if you are packaging resources -- EVEN IMAGES -- from the same origin, or that are served with 'cross-origin-resource-sharing': '*'

  2. Make sure the JSZip UMD is included in your global namespace. In my angular case, I saved it via npm i -S jszip, and then copied the node_modules/jszip/dist/jszip.js script to my src/assets folder and included it in angular.json's scripts array.

  3. Angular only: to get the jszip typescript definition file to work, copy node_modules/jszip/index.d.ts somewhere into src

  4. Download npm i -S file-saver and import it as an ES6 module (see below).

  5. Run the following function when you want the download event to occur:

import { saveAs } from 'file-saver';

async downloadData() {

    // Fetch the image and parse the response stream as a blob
    const imageBlob = await fetch('[YOUR CORS IMAGE URL]').then(response => response.blob());

    // create a new file from the blob object
    const imgData = new File([imageBlob], 'filename.jpg');

    // Copy-pasted from JSZip documentation
    var zip = new JSZip();
    zip.file('Hello.txt', 'Hello World\n');
    var img = zip.folder('images');
    img.file('smile.gif', imgData, { base64: true });
    zip.generateAsync({ type: 'blob' }).then(function(content) {
      saveAs(content, 'example.zip');
    });
  }
Bendix answered 11/11, 2020 at 18:41 Comment(0)
D
1

First of all you need to download all the images with ajax. if they are on the same domain you are in luck, otherwise you need CORS or a proxy.

var xhr = new XMLHttpRequest();

xhr.addEventListener('load', function(){
   if (xhr.status == 200){
      //Do something with xhr.response (not responseText), which should be a Blob
   }
});

xhr.open('GET', 'http://target.url');
xhr.responseType = 'blob';
xhr.send(null);

When you got the image you have to manipulate the src in all <img>'s either you replace them with base64 or referring them to a folder were you have put them in a folder with JSZip

var reader = new FileReader();
reader.onload = function() {
    showout.value = this.result;
};
reader.readAsDataURL(xhr.response);
Duffy answered 29/10, 2014 at 16:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.