zip.js官方网站为:https://stuk.github.io/jszip/html
在此说明,下面的例子基本上来自官方示例,你们能够作参考,官方示例地址为:https://stuk.github.io/jszip/documentation/examples.htmlnode
官方例子支持在线演示效果。jquery
研究的目的是:如何获取zip包中的信息并读取传输(其实使用JAVA或者node.js更容易实现,之因此使用js也是由于业务的特殊性)。git
准备库:github
jszip.js能够去该地址下载:https://github.com/Stuk/jszipchrome
下载成功解压是这样的,如图所示:浏览器
<script src="jszip.js"></script>和<script src="FileSaver.js"></script>分别在dist和vendor目录下
jszip-utils.js能够去该地址下载:https://github.com/Stuk/jszip-utils
app
jszip-utils.js 在dist目录下
1、使用zip.js压缩生成zip包网站
源码以下:this
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> <script src="jszip.js"></script> <script src="jszip-utils.js"></script> <script src="FileSaver.js"></script> </head> <body> <input type="button" value="生成zip" onclick="test()"/> <script> function test(){ var zip = new JSZip(); zip.file("1.in", "1 1"); zip.file("1.out","2"); zip.generateAsync({type:"blob"}) .then(function(content) { // see FileSaver.js saveAs(content, "example.zip"); }); } </script> </body> </html>
2、读取zip包内容并输出文件目录
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> <script src="http://sqqihao.github.io/codes/zipjs/zip.js"></script> <script src="http://gildas-lormeau.github.io/zip.js/demos/mime-types.js"></script> <script src="http://apps.bdimg.com/libs/jquery/1.9.0/jquery.js"></script> <script src="http://sqqihao.github.io/codes/zipjs/UnZipArchive.js"></script> <style> code{ display: block; padding: 10px; background: #eee; } </style> </head> <body> <div> <h1> 兼容性 </h1> <div> <p> zip.js能够在全部的chrome浏览器和firefox浏览器中运行, 能够在safari6和IE10,以及IE10以上运行; </p> <p> 若是要在IE9和safari中运行需添加, 具体能够参考官网的说明: </p> <code> 1:并引用这个JS: https://bitbucket.org/lindenlab/llsd/raw/7d2646cd3f9b/js/typedarray.js </code> </div> <h2> demo </h2> <div> <input type="file" id="file"> </div> <ul id="dir"> </ul> <script> $("#file").change(function (e) { var file = this.files[0]; window.un = new UnZipArchive( file ); un.getData( function() { var arr = un.getEntries(); var str = ""; for(var i=0; i<arr.length; i++ ) { str += "<li onclick=download('"+arr[i]+"')>"+arr[i]+"</li>" }; $("#dir").html( str ); }); }); var download = function ( filename ) { un.download( filename ); }; </script> </div> </body> </html>
效果如图所示:
注意事项:
不知道因为是什么缘由,若是单独将其写入某个html运行起来就会出现这样的状况,如图所示:
若是是经过git clone https://github.com/sqqihao/sqqihao.github.io
运行zip.html就会出现前面的正常解压并读取目录的结果。
另外请注意最好是经过火狐浏览器运行这段代码,不然可能出现这种状况,如图所示:
这篇文章主要创建在官方文档和这个github项目的基础上,但愿可以对小伙伴们有所帮助。