JavaScript >> Web Applications >> ZIP


How to Create ZIP files in JavaScript


Creating ZIP files by using JavaScript is a huge task if we write custom code for the same. Recently I cam across the
JSZip library which can be used to create zip files from within the browser only and there is no need to send a request to serve fro performing the ZIP operation.

Of Course, the server side programming languages like Java EE, PHP and .Net have the libraries to generate the ZIP files and send them back to the client but if you need to generate the ZIP files very frequently then using a server side technology may not be an efficient solution because of the network calls to server.

JSZip is a javascript library which can be used to create ZIP files by using JavaScript in a web applications. The following code snippet tutorial shows how to use the JSZip libary:

Using JSZip

<script type="text/javascript"
        src="https://raw.github.com/Stuk/jszip/master/jszip.js"></script>
<script>
function zip() {
    var jsZip = new JSZip();
    zip.add("test1.txt", "Test1n");
    zip.add("test2.txt", "Test2n");
    zipFile = zip.generate();
    location.href="data:application/zip;base64," + zipFile;
}
</script>

The above javascript function can be invoked on the click of a button or image which will cause the URL of current browser to point to the zip file and hence a download prompt will be generates asking the user to download the ZIP file.

It should be noted that the zip file created by the above example code will contain two files namely test1.txt and test2.txt. These files don’t exist anywhere on the file system. These two files are created by the JSZip library only add are stuffed with contents passed as the second argument to add function of jsZip object.

This means that you should have the data in some javascript variable before pushing it to some file within the zip file. The data can be text, image or video.

One can download the JSZIp library from official site
If you want to customize the name of zip file being generated then use the downloadify javascript library which can do the same for your application

JavaScript Tutorial
JavaScript at Google
8 Cross Browser jQuery Plugins
How to convert local time to EST or EDT using JavaScript
How to convert local time to PST or PDT using JavaScript

Leave Comment