Angularでzipしました
7970 ワード
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);
});
});
}
Author And Source
この問題について(Angularでzipしました), 我々は、より多くの情報をここで見つけました https://qiita.com/kawakami-kazuyoshi/items/181ef98cbf1ec7c83fd9著者帰属:元の著者の情報は、元のURLに含まれています。著作権は原作者に属する。
Content is automatically searched and collected through network algorithms . If there is a violation . Please contact us . We will adjust (correct author information ,or delete content ) as soon as possible .