Create ZIP Files in JavaScript

本文介绍了如何使用JavaScript创建ZIP文件,包括导入ZIP API、生成基本的ZIP文件,并解决了文件名生成的问题。

文章源自:http://viralpatel.net/blogs/create-zip-file-javascript/

Create ZIP Files in JavaScript

Zip is a very useful file type if I must say most used. It is the most used file format for data compression and archiving. There are number utilities available to create/generate Zip file. Also most of the programming languages comes up with API supporting to generate Zip files. I have written a couple of articles for zipping/unzipping files in Java and PHP.

While browsing internet, I came up to a very interesting website http://jszip.stuartk.co.uk/. This is JavaScript based API to generate Zip files on the fly! It’s very simple to use. All you need to do is to include the jszip javascript file in your HTML document and call its API.

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

Hello world 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" 
		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.

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. b77AewqA7.zip.part. 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");
Downloadify.create('downloadify',{
...
  data: function(){
    return zip.generate();
  },
...
  dataType: 'base64'
});

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

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值