79

Is there a way to zip files using JavaScript?? For an example, like in Yahoo mail, when you chose to download all the attachments from an email, it gets zipped and downloaded in a single zip file. Is JavaScript capable of doing that? If so, please provide a coding example.

I found this library called jszip to do the task but it has known and unresolved issues.

How do I solve the problem?

Emma
  • 27,428
  • 11
  • 44
  • 69
Isuru
  • 30,617
  • 60
  • 187
  • 303
  • possible duplicate of http://stackoverflow.com/questions/2095697/unzip-files-using-javascript – kvc Dec 22 '11 at 19:23
  • 1
    @kvc I saw that too but my question is to zip files. Not unzip. So thought of asking it as another post :) – Isuru Dec 22 '11 at 19:28
  • You might be able to create a windows shell javascript that does this but you cannot do this in the browser. – kvc Dec 22 '11 at 19:35

7 Answers7

59

JSZip has been updated over the years. Now you can find it on its GitHub repo

It can be used together with FileSaver.js

You can install them using npm:

npm install jszip --save
npm install file-saver --save

And then import and use them:

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

const zip = new JSZip();
zip.file('idlist.txt', 'PMID:29651880\r\nPMID:29303721');
zip.generateAsync({ type: 'blob' }).then(function (content) {
    FileSaver.saveAs(content, 'download.zip');
});

Then you will download a zip file called download.zip, once you've extracted it, and you can find inside a file called idlist.txt, which has got two lines:

PMID:29651880
PMID:29303721

And for your reference, I tested with the following browsers, and all passed:

  • Firefox 59.0.2 (Windows 10)
  • Chrome 65.0.3325.181 (Windows 10)
  • Microsoft Edge 41.16299.371.0 (Windows 10)
  • Internet Explorer 11.0.60 (Windows 10)
  • Opera 52 (Mac OSX 10.13)
  • Safari 11 (Mac OSX 10.13)
Jirik
  • 1,435
  • 11
  • 18
Yuci
  • 27,235
  • 10
  • 114
  • 113
  • This doesn't work for me. I get this: `UnhandledPromiseRejectionWarning: Error: blob is not supported by this platform` Also, how do I zip up an already existing file in the same directory? – jupiterjelly Jul 21 '21 at 20:41
20

If you don't care about IE, client-zip is much faster and smaller than JSZip and is meant to solve exactly this problem (yes, this is a shameless but completely relevant plug for my library ).

You would do something like this (where files could be an array of fetch Responses for example, though there are many supported inputs):

import { downloadZip } from "client-zip/index.js"
import FileSaver from "file-saver"

const content = await downloadZip(files).blob()
FileSaver.saveAs(content, "download.zip");

Essentially the same usage as in Yuci's answer but updated for 2020.

Touffy
  • 6,309
  • 22
  • 28
  • 2
    But client-zip do not compress the data – Vagner Gon Dec 30 '20 at 17:36
  • 5
    That's not necessarily a bad thing. Indeed, many browsers automatically unzip downloaded archives, so compression would only increase CPU load (for compression, and then again decompression) for no bandwidth or storage savings at all. The main reason for zipping here seems to be to achieve a one-click download of multiple attachments. – Touffy Dec 31 '20 at 13:58
  • 4
    Didn't say that is a bad thing. But you mentioned 'exactly this problem' that may sound that it should do the same stuff as JSZip. Client-zip seems awesome to do what it propouses. – Vagner Gon Dec 31 '20 at 18:02
  • 1
    All right. To be clear : I do not claim client-zip solves the same group of problems as JSZip, just the one in this question. – Touffy Jan 01 '21 at 20:57
  • the updated client-zip seems even much easier without the need of filesaver – Nick Chan Abdullah Jun 21 '21 at 03:32
  • Thanks @Touffy! This is perfect for downloading multiple attachments! – nycynik Jul 17 '21 at 23:19
  • does client-zip allow creation of folders in the zip file? – Victor Jun 07 '22 at 21:51
  • @Victor https://github.com/Touffy/client-zip/issues/6 (tl;dr : YES. Just prefix the filename with "/") – Touffy Jun 08 '22 at 07:29
  • @Touffy Is it possible to pipe multiple files into the HDD as they are being fetched? So you dont have to hold them in memory? – Mustafa Oct 03 '22 at 11:01
  • Yes. Using a Service Worker, you can stream the download to the browser window and keep a low RAM usage during the whole process. [See the demo](https://touffy.me/client-zip/demo/worker). – Touffy Oct 04 '22 at 07:20
  • Can you use this on an array of File objects to create a zip file? – Some Guy Jun 22 '23 at 06:04
  • @SomeGuy yes, naturally. – Touffy Jun 23 '23 at 07:16
11

By using JSZIP we can generate and download zip file in JavaScript. For that you have to follow the steps below

  1. Download jszip zip file from http://github.com/Stuk/jszip/zipball/master
  2. Extract the zip and find jszip.js file inside dist folder
  3. Import jszip.js file in your html file like below

    <script type="text/javascript" src="jszip.js"></script>
    
  4. Add below function in your code and call it

    onClickDownload: function () {
        var zip = new JSZip();
        for (var i = 0; i < 5; i++) {
            var txt = 'hello';
            zip.file("file" + i + ".txt", txt);
        }
        zip.generateAsync({
            type: "base64"
        }).then(function(content) {
            window.location.href = "data:application/zip;base64," + content;
        });       
    }
    
  5. You can download sample code from my git repository here (GIT link)

Samuel Liew
  • 76,741
  • 107
  • 159
  • 260
Sangeetharaj
  • 169
  • 3
  • 14
  • 5
    It's a pretty bad idea to generate the output in Base64, and even a worse idea to use a Data URI like that. A waste of memory and CPU. Use a blob URL instead. – Brad Sep 23 '19 at 03:08
  • Excellent, I changed the type to 'blob' and it worked like a charm! I used an anchor link on the page to trigger the download instead of changing the page url. var uriContent = URL.createObjectURL(contentBlob); var lnkDownload = document.getElementById('lnkDownload'); lnkDownload.download = 'MyDownload.zip'; lnkDownload.href = uriContent; lnkDownload.click(); – tgraupmann May 13 '20 at 21:57
6

I developed a new solution to generate zip files using JavaScript. The solution is in the public domain.

The Zip class.

Zip {

    constructor(name) {
        this.name = name;
        this.zip = new Array();
        this.file = new Array();
    }
    
    dec2bin=(dec,size)=>dec.toString(2).padStart(size,'0');
    str2dec=str=>Array.from(new TextEncoder().encode(str));
    str2hex=str=>[...new TextEncoder().encode(str)].map(x=>x.toString(16).padStart(2,'0'));
    hex2buf=hex=>new Uint8Array(hex.split(' ').map(x=>parseInt(x,16)));
    bin2hex=bin=>(parseInt(bin.slice(8),2).toString(16).padStart(2,'0')+' '+parseInt(bin.slice(0,8),2).toString(16).padStart(2,'0'));
    
    reverse=hex=>{
        let hexArray=new Array();
        for(let i=0;i<hex.length;i=i+2)hexArray[i]=hex[i]+''+hex[i+1];
        return hexArray.filter((a)=>a).reverse().join(' '); 
    }
    
    crc32=r=>{
        for(var a,o=[],c=0;c<256;c++){
            a=c;
            for(var f=0;f<8;f++)a=1&a?3988292384^a>>>1:a>>>1;
            o[c]=a;
        }
        for(var n=-1,t=0;t<r.length;t++)n=n>>>8^o[255&(n^r[t])];
        return this.reverse(((-1^n)>>>0).toString(16).padStart(8,'0'));
    }
    
    fecth2zip(filesArray,folder=''){
        filesArray.forEach(fileUrl=>{
            let resp;               
            fetch(fileUrl).then(response=>{
                resp=response;
                return response.arrayBuffer();
            }).then(blob=>{
                new Response(blob).arrayBuffer().then(buffer=>{
                    console.log(`File: ${fileUrl} load`);
                    let uint=[...new Uint8Array(buffer)];
                    uint.modTime=resp.headers.get('Last-Modified');
                    uint.fileUrl=`${this.name}/${folder}${fileUrl}`;                            
                    this.zip[fileUrl]=uint;
                });
            });             
        });
    }
    
    str2zip(name,str,folder){
        let uint=[...new Uint8Array(this.str2dec(str))];
        uint.name=name;
        uint.modTime=new Date();
        uint.fileUrl=`${this.name}/${folder}${name}`;
        this.zip[uint.fileUrl]=uint;
    }
    
    files2zip(files,folder){
        for(let i=0;i<files.length;i++){
            files[i].arrayBuffer().then(data=>{
                let uint=[...new Uint8Array(data)];
                uint.name=files[i].name;
                uint.modTime=files[i].lastModifiedDate;
                uint.fileUrl=`${this.name}/${folder}${files[i].name}`;
                this.zip[uint.fileUrl]=uint;                            
            });
        }
    }
    
    makeZip(){
        let count=0;
        let fileHeader='';
        let centralDirectoryFileHeader='';
        let directoryInit=0;
        let offSetLocalHeader='00 00 00 00';
        let zip=this.zip;
        for(const name in zip){
            let modTime=()=>{
                lastMod=new Date(zip[name].modTime);
                hour=this.dec2bin(lastMod.getHours(),5);
                minutes=this.dec2bin(lastMod.getMinutes(),6);
                seconds=this.dec2bin(Math.round(lastMod.getSeconds()/2),5);
                year=this.dec2bin(lastMod.getFullYear()-1980,7);
                month=this.dec2bin(lastMod.getMonth()+1,4);
                day=this.dec2bin(lastMod.getDate(),5);                      
                return this.bin2hex(`${hour}${minutes}${seconds}`)+' '+this.bin2hex(`${year}${month}${day}`);
            }                   
            let crc=this.crc32(zip[name]);
            let size=this.reverse(parseInt(zip[name].length).toString(16).padStart(8,'0'));
            let nameFile=this.str2hex(zip[name].fileUrl).join(' ');
            let nameSize=this.reverse(zip[name].fileUrl.length.toString(16).padStart(4,'0'));
            let fileHeader=`50 4B 03 04 14 00 00 00 00 00 ${modTime} ${crc} ${size} ${size} ${nameSize} 00 00 ${nameFile}`;
            let fileHeaderBuffer=this.hex2buf(fileHeader);
            directoryInit=directoryInit+fileHeaderBuffer.length+zip[name].length;
            centralDirectoryFileHeader=`${centralDirectoryFileHeader}50 4B 01 02 14 00 14 00 00 00 00 00 ${modTime} ${crc} ${size} ${size} ${nameSize} 00 00 00 00 00 00 01 00 20 00 00 00 ${offSetLocalHeader} ${nameFile} `;
            offSetLocalHeader=this.reverse(directoryInit.toString(16).padStart(8,'0'));
            this.file.push(fileHeaderBuffer,new Uint8Array(zip[name]));
            count++;
        }
        centralDirectoryFileHeader=centralDirectoryFileHeader.trim();
        let entries=this.reverse(count.toString(16).padStart(4,'0'));
        let dirSize=this.reverse(centralDirectoryFileHeader.split(' ').length.toString(16).padStart(8,'0'));
        let dirInit=this.reverse(directoryInit.toString(16).padStart(8,'0'));
        let centralDirectory=`50 4b 05 06 00 00 00 00 ${entries} ${entries} ${dirSize} ${dirInit} 00 00`;
        this.file.push(this.hex2buf(centralDirectoryFileHeader),this.hex2buf(centralDirectory));                
        let a = document.createElement('a');
        a.href = URL.createObjectURL(new Blob([...this.file],{type:'application/octet-stream'}));
        a.download = `${this.name}.zip`;
        a.click();              
    }
}

Then, create a new object Zip.

  z=new Zip('myZipFileName');

You you can:

  • Load files of your directory to zip object with fecth2zip(filesArray,folder).
  filesArray=[
    'file01.ext',
    'file02.ext',
    'file...'
  ];
  z.fecth2zip(filesArray,'public/');
  • Create a new file from a string with str2zip(nameFile,content,directory).
  z.str2zip('test.txt','content','public/teste/');
  • Or upload to zip.

    Put onchange event into the input file and send the files to function files2zip(this.files).

  <input type="file" onchange="z.files2zip(this.files)" value='files' multiple>

After placing all the objects inside your Zip object file, just download it.

  <input type="button" onclick="z.makeZip()" value='Zip'>

The class can also be found here: https://github.com/pwasystem/zip/

Spiderpoison
  • 95
  • 2
  • 9
  • Great idea - nicely written - but doesn't work for me. I tried the following and it downloaded a file but it wasn't a valid zip? var z=new Zip('myZipFileName'); z.str2zip('test.txt','content'); z.makeZip(); – Simon Sawyer Jul 21 '23 at 11:36
4

This is an older question but I ran across it searching for a solution to creating a zip archive.

For my use case, I'm creating several thousand zip archives in node.js from a very large logger source every minute consisting of up to 200 files in each archive.

I had tried JSZip with very poor results due to performance issues and a memory leak not worth the time to track down. Since my use case is fairly extreme, it's quite the stress test.

I came across another pure javascript zip library worth mentioning here for others to check out.

I ended up using fflate.

https://github.com/101arrowz/fflate

This library has been extremely performant. I'm only using the zip archive feature with level 9 compression, but fflate is a full featured library which works server side and complete browser support (2011+). I'm not including any examples here as fflate documentation is very complete. I'd highly recommend it as an alternative.

MarkM
  • 141
  • 1
  • 4
3

I'd recommend going straight to using Node's built-in library Zlib for this, which includes images; encode in base 64 using "buffers". Rather than using npm packages. Reasons being:

  • Zlib is a Node native library - has been kept up-to-date for nearly 10 years now - so the proofs there for long-term supports
  • Node allows you work with Buffers - i.e. you can convert your text string/images to the raw binary data and compress it that way with Zlib
  • Easily compress and decompress large files - leverage node streams to compress files in MBs or GBs

The fact you are using jszip, would allow me to guess that you are using npm as well as node; assumes you have set up your environment correctly, i.e. node installed globally.

Example: input.txt compressed to become input.txt.gz

const zlib = require('zlib');
const fs = require('fs');
const gzip = zlib.createGzip();
const input = fs.createReadStream('input.txt');
const output = fs.createWriteStream('input.txt.gz');

input.pipe(gzip).pipe(output);

Step 1: So you require each of the native modules from node - require is part of ES5. Zlib as previously mentioned, and fs module, the File System module.

const zlib = require('zlib');
const fs = require('fs');

Step 2: The fs module, this allows you to create a readstream, are specifically called to read chunks of data. This will return a readstream object; readable stream

const input = fs.createReadStream(FILE PATH HERE);

__Note: This readstream object then gets piped again; this chaining of pipes on readsteam objects can occur endlessly, making pipes very flexible.

ReadStream.pipe(DoesSomething).pipe(SomethingElse).pipe(ConvertToWriteStream)

Step 3: The readstream object, that has been piped and compressed is then converted to writestream object.

const output = fs.createWriteStream('input.txt.gz');

input.pipe(gzip).pipe(output); // returned filename input.txt.gz, within local directory

So this library allows you easily enter a file path and decide where you want your compressed file to be. You can also choose to do the reverse, if need be.

Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
A. Tran
  • 333
  • 1
  • 5
  • 13
  • 7
    Thanks for sharing. However, I guess the question sought a browser-side solution rather than a server-side's. Any idea on the browser-side? Thanks. – Yuci Apr 15 '18 at 07:44
1

With the new HTML5 file APIs and the typed arrays, you can pretty much do anything you want in JavaScript. However, the browser support isn't going to be great. I'm guessing that's what you meant by "unresolved issues". I would recommend, for the time being, to do it on the server. For example, in PHP, you could use this extension.

Alex Turpin
  • 46,743
  • 23
  • 113
  • 145