Thursday, April 26, 2012

Creating a ZIP file using JavaScript

Hi Guys,
             We have 'n' number of tools which generates  ZIP files but creating the ZIP files using JavaScript is different. To create a ZIP file using Java script we need to download the jszip.js and include it to your html file.


Knowledge Base : 




Sample Code:
            http://viralpatel.net/blogs/2012/01/create-zip-file-javascript.html

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"
        src="https://raw.github.com/Stuk/jszip/master/jszip.js"></script>

Step 2. Generate Hello world ZIP

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





















<HTML>
<HEAD>
    <script type="text/javascript" src="jszip.js"></script>
</HEAD>
 
<BODY>
 
    <input type="button" onclick="create_zip()" value="Create Zip"></input>
 
</BODY>
<SCRIPT>
 
function create_zip() {
    var zip = new JSZip();
    zip.add("hello1.txt", "Hello First World\n");
    zip.add("hello2.txt", "Hello Second World\n");
    content = zip.generate();
    location.href="data:application/zip;base64," + content;
}
 
</SCRIPT>
</HTML>
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.

No comments:

Post a Comment