JSZip
Create, read and edit .zip files with JavascriptHow?
Why?
- JavaScript today is capable of generating a lot of data. The easiest way to deliver multiple files to your users is in a zip file. Instead of wasting server resources and bandwidth you can get the client to do it for you.
- Because it's cool!
Tell me more!
Browser support
Yes | Yes | Yes | Yes | Yes |
Tested with the latest version | Tested with 3.0 / 3.6 / latest version | Tested with the latest version | Tested with the latest version | Tested with IE 6 / 7 / 8 / 9 / 10 |
While JSZip should work everywhere, the tricky part is to give the zip file to the user.
Browser support for data URI scheme with zip
7.5+ | 3.0+ | Yes | Yes | No |
Filename is "default.zip" | Filename is random alphanumeric with ".part" extension | Filename is "Unknown" (no extension) | Filename is "download.zip" on OSX and Linux, and just "download" on Windows (issue #9) | Only supports data URLs for some content. (May be able to use MHTML?) |
Filename problems
The biggest issue with JSZip is that the filenames are very awkward, Firefox generates filenames such as a5sZQRsx.zip.part
(see bugs 367231 and 532230), and Safari isn't much better with just Unknown
. Sadly there is no pure Javascript solution (and working in every browsers) to this. However...
Solution-ish: Downloadify
Downloadify uses a small Flash SWF to download files to a user's computer with a filename that you can choose. Doug Neiner has added the dataType
option to allow you to pass a zip for downloading. Follow the Downloadify demo with the following changes:
zip = new JSZip(); zip.add("Hello.", "hello.txt"); Downloadify.create('downloadify',{ ... data: function(){ return zip.generate(); }, ... dataType: 'base64' });
Other solution-ish: Blob URL
With some recent browsers come a new way to download Blobs (a zip file for example) : blob urls. The download attribute on <a> allows you to give the name of the file. Blob urls start to be widely supported but this attribute is currently only supported in Chrome and Firefox (>= 20). See the example.
var blob = zip.generate({type:"blob"}); myLink.href = window.URL.createObjectURL(blob); myLink.download = "myFile.zip";
Usage with Google Gears
Franz Buchinger has written a brilliant tutorial on using JSZip with Google Gears (part 2). If you want to let your Gears users download several files at once I really recommend having a look at some of his examples.
Reading a zip file from an ajax call
When doing an ajax call to get the binary data, the browser will try to interpret the binary as text, corrupting it. The solution is to set the mimetype to 'text/plain; charset=x-user-defined'. This solution works well in all browsers but IE. If you need IE support, please see what is done in the file test/index.html.
An other solution is to use a modern browser (supporting xhr2) : setting xhr.type = 'arraybuffer';
will do the trick, JSZip supports ArrayBuffers. Please see the example.
Reading a local zip file (File API)
JSZip supports (if available in the browser) the File API : reading a local zip file is simple : new JSZip(readerEvent.target.result);
. Please see the complete example for more details.
Documentation
new JSZip()
new JSZip(data [,options])
load()
for more details and this for the limitations.data
(same types as load()
) the content of the zip file to load.options
(Object) options to pass to the load()
method..new JSZip(zipDataFromXHR, {base64:false}); // same as var zip = new JSZip(); zip.load(zipDataFromXHR, {base64:false});
file(name)
name
(String) the name of the file.null
otherwise. The file has the following structure :
-
name
the absolute path of the file -
data
the data contained in the file -
options
the options of the file. The available options are :-
base64
, boolean, cf file(name, data [,options]) -
binary
, boolean, cf file(name, data [,options]) -
dir
, boolean, true if this is a directory -
date
, date, cf file(name, data [,options])
-
-
asText()
, string, the content as an utf8 string (utf8 encoded if necessary). -
asBinary()
, string, the content as binary (utf8 decoded if necessary). -
asArrayBuffer()
, ArrayBuffer, need a compatible browser. -
asUint8Array()
, Uint8Array, need a compatible browser.
var zip = new JSZip(); zip.file("file.txt", "content"); zip.file("file.txt").name // "file.txt" zip.file("file.txt").data // "content" zip.file("file.txt").options.dir // false // utf8 example var zip = new JSZip(zipFromAjaxWithUTF8); zip.file("amount.txt").data // "€15" zip.file("amount.txt").asText() // "€15" zip.file("amount.txt").asArrayBuffer() // an ArrayBuffer containing €15 zip.file("amount.txt").asUint8Array() // an Uint8Array containing €15
file(regex)
regex
(RegExp) the regex to use.var zip = new JSZip(); zip.file("file1.txt", "content"); zip.file("file2.txt", "content"); zip.file(/file/); // array of size 2 // example with a relative path : var folder = zip.folder("sub"); folder .file("file3.txt", "content") // relative path from folder : file3.txt .file("file4.txt", "content"); // relative path from folder : file4.txt folder.file(/file/); // array of size 2 folder.file(/^file/); // array of size 2, the relative paths start with file // arrays contain objects in the form: // {name: "file2.txt", data: "content", dir: false}
file(name, data [,options])
name
(String) the name of the file.data
(String/ArrayBuffer/Uint8Array) the content of the file.options
(Object) the options :
-
base64
(boolean) set totrue
if the data is base64 encoded. For example image data from a<canvas>
element. Plain text and HTML do not need this option. -
binary
(boolean) defaults totrue
if the data is base64 encoded,false
otherwise. If set to false then UTF-8 characters will be encoded. If the data is an ArrayBuffer or an Uint8Array, this will be set to true. -
date
(Date) use it to specify the last modification date. If not set the current date is used. -
optimizedBinaryString
(boolean), default false. Set it to true if (and only if) the input has already been prepared with a 0xFF mask.
zip.add("Hello.txt", "Hello World\n"); zip.add("smile.gif", "R0lGODdhBQAFAIACAAAAAP/eACwAAAAABQAFAAACCIwPkWerClIBADs=", {base64: true}); zip.add("magic.txt", "U2VjcmV0IGNvZGU=", {base64: true, binary: false}); zip.add("Xmas.txt", "Ho ho ho !", {date : new Date("December 25, 2007 00:00:01")}); zip.add("folder/file.txt", "file in folder"); zip.add("animals.txt", "dog,platypus\n").add("people.txt", "james,sebastian\n"); // result : Hello.txt, smile.gif, magic.txt, Xmas.txt, animals.txt, people.txt, // folder/, folder/file.txt
folder(name)
name
(String) the name of the directory.zip.folder("images"); zip.folder("css").add("style.css", "body {background: #FF0000}"); // or specify an absolute path (using forward slashes) zip.add("css/font.css", "body {font-family: sans-serif}") // result : images/, css/, css/style.css, css/font.css
folder(regex)
regex
(RegExp) the regex to use.var zip = new JSZip(); zip.folder("home/Pierre/videos"); zip.folder("home/Pierre/photos"); zip.folder("home/Jean/videos"); zip.folder("home/Jean/photos"); zip.folder(/videos/); // array of size 2 zip.folder("home/Jean").folder(/^vid/); // array of 1
remove(name)
Delete a file or folder.
name
(String) the name of the file/folder to delete.var zip = new JSZip(); zip.add("Hello.txt", "Hello World\n"); zip.add("temp.txt", "nothing").remove("temp.txt"); // result : Hello.txt zip.folder("css").add("style.css", "body {background: #FF0000}"); zip.remove("Hello.txt").remove("css"); //result : empty zip
generate(options)
options
(Object) the options to generate the zip file :
-
base64
(boolean) deprecated, use "type" instead.false
to get the result as a raw byte string. Default :true
, encode as base64. -
compression
(String) the compression method to use."STORE"
(no compression) by default, you can use"DEFLATE"
(include the file jszip-deflate.js) or write your own. -
type
(String) the type of zip to return. The possible values are :-
base64
(default) : the result will be a string, the binary in a base64 form. -
string
: the result will be a string in "binary" form, 1 byte per char. -
uint8array
: the result will be a Uint8Array containing the zip. This requires a compatible browser. -
arraybuffer
: the result will be a ArrayBuffer containing the zip. This requires a compatible browser. -
blob
: the result will be a Blob containing the zip. This requires a compatible browser.
-
JSZip.support
). This method will throw an exception otherwise.
content = zip.generate(); location.href="data:application/zip;base64,"+content;
content = zip.generate({type:"string"}); for (var c = 0; c < content.length; c++) { console.log(content.charCodeAt(c)); // do other things }
load(data, options)
data
(String/ArrayBuffer/Uint8Array) the zip fileoptions
(Object) the options to load the zip file :
-
base64
(boolean)true
if the data is base64 encoded,false
for binary. Default :false
. -
checkCRC32
(boolean)true
if the read data should be checked against its CRC32. Default :false
.
var zip = new JSZip(); zip.load(zipDataFromXHR);
Zip features supported by this method
- Compression (
DEFLATE
with jszip-deflate.js) - zip with data descriptor
- ZIP64
- UTF8 in file name, UTF8 in file content
Zip features not (yet) supported
- password protected zip
- multi-volume zip
filter(predicate)
predicate
(function) the predicate to use : function (relativePath, file) {...}
It takes 2 arguments : the relative path and the file.
-
relativePath
(String) The filename and its path, reliatively to the current folder. -
file
(Object) The file being tested. Like the result offile(name)
, the file has the form{name:"...", data:"...", options:{...}}
. - Return true if the file should be included, false otherwise.
var zip = new JSZip().folder("dir"); zip.file("readme.txt", "content"); zip.filter(function (relativePath, file){ // relativePath == "readme.txt" // file = {name:"dir/readme.txt",data:"content",options:{...}} return true/false; });
JSZip.support
If the browser supports them, JSZip can take advantage of some new features : ArrayBuffer, Blob, Uint8Array. To know if JSZip can use them, you can check the JSZip.support object. It contains the following properties :
-
arraybuffer
: true if JSZip can read and generate ArrayBuffer, false otherwise. -
uint8array
: true if JSZip can read and generate Uint8Array, false otherwise. -
blob
: true if JSZip can read and generate Blob, false otherwise.
Loading zip files, limitations
All the features of zip files are not supported. Classic zip files will work but encrypted zip, multi-volume, etc are not supported and the load() method will throw an Error
.
ZIP64 files can be loaded, but only if the zip file is not "too big". ZIP64 uses 64bits integers but Javascript represents all numbers as 64-bit double precision IEEE 754 floating point numbers (see section 8.5). So, we have 53bits for integers and bitwise operations treat everything as 32bits. So if all the 64bits integers can fit into 32 bits integers, everything will be fine. If it's not the case, you will have other problems anyway (see next limitation).
An other limitation comes from the browser (and the machine running the browser). A compressed zip file of 10M is common and easily opened by desktop application, but not in a browser. The processing of such a beast is likely to be painful : the browser will eat hundreds of megabytes while using CPU like never.
If you use an old browser, things will be worse. For example, IE6 and IE7 are quite slow to to execute the unit tests, and they completely freeze as soon as they try to handle larger files.
Conclusion : reading small files is OK, reading others is not.
Reading and generating a zip file won't give you back the same file. Some data are discarded (file metadata) and other are added (subfolders).
Changelog
1.0.1 2013-03-04
- Fixed an issue when generating a compressed zip file with empty files or folders, see #33.
- With bad data (
null
orundefined
), asText/asBinary/asUint8Array/asArrayBuffer methods now return an empty string, see #36.
1.0.0 2013-02-14
First release after a long period without version.
相关推荐
Steps to record and edit powerful macros to quickly and efficiently edit files Using "copied" and "selected" variables for dynamic macros Use copied and selected text in macros to dramatically ...
多语言支持,通过简单设置XML即可完成 (Demo) <br/>All labels, buttons, tooltips and messages are located in external XML files, so that the language of the editor can be switched with a single...
* The plugin requires Flash Player 9 or better and javascript. Please make sure you have both. * There have been some cases where WordPress' Automatic Plugin Upgrade feature breaks the plugin. After ...
matlab
操作系统课程设计基于C++实现的操作系统仿真虚拟页式存储管理项目源代码
内容概要:本文详细介绍了西门子S7-1500 PLC与V90伺服在定长切断应用中的具体实现方法和技术要点。首先,文章展示了如何利用TIA Portal V16平台配置工艺对象“CuttingAxis”,并解释了关键参数如每转脉冲数、丝杆导程、减速比等的作用。接着,针对可能出现的问题,如轴运行抖动、控制字状态丢失等进行了深入探讨,并提供了相应的解决措施,比如调整前馈参数、修改报文配置等。此外,还分享了一些提高系统性能的小技巧,例如启用动态限制选项、优化速度前馈与位置环配合等。最后,强调了该方案在包装机械和线材加工领域的广泛应用前景及其优势所在。 适合人群:从事工业自动化相关工作的工程师和技术人员,尤其是那些希望深入了解和掌握西门子PLC与伺服系统集成应用的专业人士。 使用场景及目标:适用于需要实现高精度定长切断操作的企业或项目,旨在帮助用户构建稳定可靠的控制系统,确保生产效率和产品质量。 其他说明:文中不仅涵盖了理论知识讲解,还包括大量实际案例分析以及代码示例,便于读者更好地理解和应用所学内容。同时提醒读者关注硬件配置、软件编程、参数调节等多个方面,以达到最佳效果。
2023年计算机二级Office选择题考前模拟.docx
目前可以新建目录,具体自己看代码
基于SpringBoot网上超市,系统包含两种角色:用户、管理员,系统分为前台和后台两大模块,主要功能如下: 1 管理员功能实现 商品信息管理 管理员可以通过提交商品名称查询商品,并查看该商品的用户评论信息。 用户管理 管理员通过提交用户名来获取用户资料,对有异常情况的用户信息进行修改,并可以详细查看用户资料。 商品评价管理 管理员审核用户对商品的评价,经过审核的评价才会显示,并可以统计商品评价信息。 已支付订单 管理员查看已支付的订单,并逐个进行订单发货。 2 用户功能实现 商品信息 用户可以收藏、立即购买商品,或对商品进行评价,同时将商品添加到购物车。 购物车 用户可以直接下单购买购物车中的商品,或删除购物车中的商品。 确认下单 用户选择地址,查看支付金额信息,以确认订单之前的所有细节。 已支付订单 用户查看已支付的订单,若对购买商品产生后悔,可以申请退款。 二、项目技术 开发语言:Java 数据库:MySQL 项目管理工具:Maven Web应用服务器:Tomcat 前端技术:Vue、 后端技术:SpringBoot框架 三、运行环境 操作系统:Windows、macOS都可以 JDK版本:JDK1.8以上版本都可以 开发工具:IDEA、Ecplise都可以 数据库: MySQL 5.7/8.0版本均可 Tomcat:7.x、8.x、9.x版本均可 Maven:任意版本都可以
1_媒工十佳决赛RUNDOWN 2.xlsx
c#联合opencvsharp开发的视觉源码程序 包含模板匹配,找线找圆,预处理等功能 全部源码,包含图像显示控件,绘制roi
基于STC89C52单片机的信号发生器20172086102何雨莉_3.zip
2023年西南大学网络与继续教育学院楼宇自动化作业答案.docx
内容概要:本文详细介绍了基于SpringBoot和Vue构建的智慧养老手表管理系统的关键技术和实现细节。系统主要由家长和养老院管理员两种角色组成,家长可以通过智能手表实时查看老人的健康数据,而管理员则可以进行更全面的数据管理和权限控制。文中重点讨论了家庭树功能的实现,包括使用MyBatis的动态SQL处理复杂的家庭关系查询,以及前端用Vue的el-tree组件展示家庭树结构。健康数据监控方面,系统利用SpringBoot的@Scheduled定时任务生成日报,并通过ECharts进行数据可视化。此外,还涉及了权限控制、加好友功能、熔断机制等多个方面的技术实现。 适合人群:具有一定编程经验的开发者,尤其是熟悉SpringBoot和Vue框架的工程师。 使用场景及目标:适用于开发类似智慧养老系统的项目,旨在提高老年人健康管理的效率和安全性。目标是通过智能手表实时监测老人健康状况,提供及时的健康报告和预警,同时确保系统的稳定性和安全性。 其他说明:文中提到的技术细节对于理解和实现类似的前后端分离架构非常有帮助,特别是关于MySQL 5.7的使用和优化,以及如何处理第三方设备接口的不稳定问题。
2023年计算机二级资料.doc
2023年电大数据结构形成性考核册.doc
网络工程师易错100题 2025年
2023年电子商务技能竞赛方案.doc
2024年大数据软件项目深度研究分析报告.docx
内容概要:本文详细介绍了利用Matlab/Simulink构建输电线路单相接地故障测距模型的方法。首先,通过建立110kV输电线路的Simulink模型,采用Bergeron模型作为线路参数。接着,利用小波变换提取故障行波的模极大值点,结合凯伦布尔变换消除工频分量,从而精确计算故障位置。文中提供了详细的代码实现步骤,包括信号预处理、小波分解、模极大值检测以及时间差计算等。此外,还讨论了常见调试经验和避坑指南,如采样率设置、接地电阻限制等。最后,通过多个测试案例验证了模型的有效性和准确性。 适合人群:从事电力系统故障诊断的研究人员和技术人员,尤其是对小波变换和凯伦布尔变换感兴趣的工程师。 使用场景及目标:适用于输电线路单相接地故障的精确定位,旨在提高电力系统的可靠性和维护效率。通过掌握本文提供的方法,技术人员能够快速准确地找到故障点,减少停电时间和维修成本。 其他说明:本文不仅提供了理论解释,还包括具体的代码实现和调试建议,有助于读者更好地理解和应用所学知识。