ZIP (file format)

Let us see how to generate a simple ZIP file in JavaScript.

Sample ZIP in JavaScript

Let us create a helloworld ZIP file which contains two text files, hello1.txt and hello2.txt.

Step 1. Import jszip JavaScript

Include the jszip javascript file in the HTML document where you want to generate ZIP files. You can download the jszip package and include it in HTML or directly include the jszip javascript through git repository.

<script type="text/javascript"

Step 2. Generate Hello world ZIP

Following code snippet is HTML file which contains Javascript code to generate ZIP file.

    <script type="text/javascript" src="jszip.js"></script>
    <input type="button" onclick="create_zip()" value="Create Zip"></input>
function create_zip() {
    var zip = new JSZip();
    zip.add("hello1.txt", "Hello First Worldn");
    zip.add("hello2.txt", "Hello Second Worldn");
    content = zip.generate();
    location.href="data:application/zip;base64," + content;

In above code snippet, we have a button “Create Zip” which calls javascript function create_zip(). This function calls jszip API to generate ZIP file.

Online Demo

Check the online demo.

Filename Problem

If you have tried above demo in Firefox or Safari, you may have noticed the file that is generated has weird name: e.g. This is because of existing bugs 367231 and 532230. However jszip comes with a unique workaround of this problem by using Downloadify.

zip = new JSZip();
zip.add("Hello.", "hello.txt");
  data: function(){
    return zip.generate();
  dataType: 'base64'

Hope this basic demo will help you get going with Client side ZIP file creation in JavaScript.

Enhanced by Zemanta

Leave a Reply

Your email address will not be published. Required fields are marked *