Angularでzipしました


Angularで画像ファイルとテキストファイルをzip圧縮しました。

使ったライブラリ

インストール

npm install jszip

Angularに読み込ませる

angular.json
...
            "scripts": [
              "node_modules/jszip/dist/jszip.min.js"
            ],
...

使用する準備

foo.component.ts
declare var JSZip: any; // 宣言する

@Component({
  selector: 'app-foo',
  templateUrl: './foo.component.html',
  styleUrls: ['./foo.component.scss']
})
export class FooComponent {

  zipFile() {
    const zip = new JSZip(); // new

  }

}

圧縮して、それをダウンロードしてみる

foo.component.ts
  zipFile() {
    const zip = new JSZip();

    // 自サイトの画像をURLから読み込む
    this.toDataUrl('/assets/img/foo.png', base64image => {
      // fooカテゴリの中に画像を保存
      // formatは、data_urlからMIME情報を削除したBase64
      const base64image2  = base64image.replace(/^data:image\/(png|jpeg);base64,/, '');
      const filenameMatch = base64image.match(/^data:image\/(png|jpeg);base64,/);
      zip.folder('foo').file(`bar.${filenameMatch[1]}`, base64image2, {base64: true});

      // Textをfooカテゴリに保存
      zip.folder('foo').file('baz.txt', 'test text\n');

      // Zipを作成
      zip.generateAsync({type: 'base64'}).then(base64 => {

        // Zipを確かめるためにダウンロードしてみる
        const a = document.createElement('a');
        a.href = `data:application/zip;base64,${base64}`;
        a.download = 'foo.zip';

        a.style.display = 'none';
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
      });
    });
  }