Search code examples
reactjsdownloadziptsx

React-tsx-Download Multiple image file in Zip format


I want to download zip which contains the multiple images, I use the js-zip but it does not allow me to use jszip-util its show Can not find name JSZipUtils for that because of my TSX file i think. here is some code which I tried..

    import * as React from 'react';
    import  JSZip from 'jszip';
    import FileSaver from 'file-saver';

    class ZipDemo extends React.Component{
        download =()=>{
        let links:string[]=[
            "https://sequenceimagestaging.blob.core.windows.net/retouch/3xl/100/1610004/one.jpg?v=1569588865599",
             "https://sequenceimagestaging.blob.core.windows.net/retouch/3xl/900/2411015/two.jpg?v=1569588865599",
             "https://sequenceimagestaging.blob.core.windows.net/retouch/l/200/3310029/three.jpg?v=1569588865599",
             "https://sequenceimagestaging.blob.core.windows.net/retouch/m/300/3237036/four.jpg?v=1569588865599",
             "https://sequenceimagestaging.blob.core.windows.net/retouch/s/400/5372009/five.jpg?v=1569588865599"
        ];
        var zip = new JSZip();
        var count = 0;
        var zipFilename = "Pictures.zip";  
        links.forEach(function (url, i) {
          var filename = links[i];
          filename = filename.replace(/[\/\*\|\:\<\>\?\"\\]/gi, '').replace("httpssequenceimagestaging.blob.core.windows.netretouch","");
          JSZipUtils.getBinaryContent(url, function (err, data) {
            if (err) {
              throw err;
            }
            zip.file(filename, data, { binary: true });
            count++;
            if (count == links.length) {
              zip.generateAsync({ type: 'blob' }).then(function (content) {
                FileSaver.saveAs(content, zipFilename);
              });
            }
          });
        });
    }

    render() { 
        return (  
            <div>
                <button onClick={this.download}>click me </button>
            </div>
        );
    }
}

export default ZipDemo;

I took reference from jsfiddle


Solution

  • let blob = fetch(url).then(r => r.blob());
        zip1.file(filename, blob, { binary: true });
    

    add this 2 line in space of

    JSZipUtils.getBinaryContent(url, function (err, data) {
            if (err) {
              throw err;
            }
            zip.file(filename, data, { binary: true });
    

    it works very well because jszip-utils module is not available in typescript i think I am not sure, so it is the alternate way to convert the file into binary.