LoginSignup
24
18

More than 5 years have passed since last update.

[zlib.js] JavaScriptでZIP圧縮する

Last updated at Posted at 2018-12-27

JavaScriptでZIP圧縮することができるライブラリを紹介します。

zlib.js
https://github.com/imaya/zlib.js/

今回使用したJavaScriptライブラリのバージョンは下記の通りです。

JavaScriptライブラリ
Bootstrap: 3.3.7
jQuery: 3.3.1
zlib.js: 0.3.1

ライブラリの読み込み

zip.min.jsを参照します。

index.html
<script type="text/javascript" src="../../lib/zlib/zip.min.js"></script>

ZIPファイルをダウンロードする

画面上のテキストボックスやラジオボタン、プルダウンから、下記のようなJSONファイルを作成してZIP圧縮します。そのファイルをダウンロードします。

sample/sample001.json
{
    "inputText1": "あいうえお12345",
    "inputRadio1": "1",
    "select1": "3"
}

strToUtf8Array()で文字列からUTF-8の配列に変換します。zip.addFile()でZIP圧縮対象のファイルを指定します。zip.compressでZIP圧縮します。

ZIP圧縮してファイルをダウンロードする
var zip = new Zlib.Zip();
var plainData = JSON.stringify(getJsonObj());
zip.addFile(strToUtf8Array(plainData), {
    filename: strToUtf8Array('sample/sample001.json')
});
var compressData = zip.compress();

var blob = new Blob([compressData], { 'type': 'application/zip' });

if (window.navigator.msSaveBlob) {
    window.navigator.msSaveBlob(blob, 'sample.zip');
    window.navigator.msSaveOrOpenBlob(blob, 'sample.zip');
} else {
    document.getElementById('export').href = window.URL.createObjectURL(blob);
}

デモはこちら
ソースファイルはこちら

以上です。

関連記事

[zlib.js] JavaScriptでZIP解凍する
[zlib.js] JavaScriptでZIP圧縮する

24
18
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
24
18