Zip
IMPORT MODULE

A Zip file operation based on jszip.

Dependencies

The jszip script file takes the form of lazy loading,you can change the default CDN path via Global Configuration. By default: https://cdn.jsdelivr.net/npm/jszip@3/dist/jszip.min.js.

Use local path

// angular.json
{
  "glob": "**/jszip.min.js",
  "input": "./node_modules/jszip/dist",
  "output": "assets/jszip/"
}
// global-config.module.ts
const alainConfig: AlainConfig = {
  zip: {
    url: '/assets/jszip/jszip.min.js'
  }
};

Examples

    解压

    读取Zip文件信息(含内容),支持 File、URL 形式

    expand codeexpand code
    import { ChangeDetectionStrategy, ChangeDetectorRef, Component } from '@angular/core';
    import { ZipService } from '@delon/abc/zip';
    
    @Component({
      selector: 'components-zip-read',
      template: `
        <button nz-button (click)="url()">Via Url</button>
        <input type="file" (change)="change($event)" multiple="false" class="ml-sm" />
        <ol>
          <li *ngFor="let i of data">{{ i | json }}</li>
        </ol>
      `,
      changeDetection: ChangeDetectionStrategy.OnPush,
    })
    export class ComponentsZipReadComponent {
      data: any;
    
      constructor(private zip: ZipService, private cdr: ChangeDetectorRef) {}
    
      private format(data: { files: { [key: string]: { dir: string; date: Date } } }): void {
        const files = data.files;
        this.data = Object.keys(files).map(key => ({
          name: key,
          dir: files[key].dir,
          date: files[key].date,
        }));
        this.cdr.detectChanges();
      }
    
      url(): void {
        this.zip.read(`./assets/demo.zip`).then(res => this.format(res));
      }
    
      change(e: Event): void {
        const file = (e.target as HTMLInputElement).files![0];
        this.zip.read(file).then(res => this.format(res));
      }
    }
    压缩

    通过 pushUrl 可以快速将URL资源写入 Zip 实例。

    expand codeexpand code
    import { Component } from '@angular/core';
    import { ZipService } from '@delon/abc/zip';
    import * as JSZip from 'jszip';
    import { NzMessageService } from 'ng-zorro-antd/message';
    
    @Component({
      selector: 'components-zip-save',
      template: `
        <div *ngIf="instance">
          <button nz-button (click)="add()" [nzType]="'primary'">new</button>
          <button nz-button (click)="download()" class="ml-sm">download</button>
          <nz-table [nzData]="data" [nzFrontPagination]="false" [nzShowPagination]="false" class="mt-sm">
            <thead>
              <tr>
                <th><span>path</span></th>
                <th><span>url</span></th>
              </tr>
            </thead>
            <tbody>
              <tr *ngFor="let i of data; let index = index">
                <td><input nz-input [(ngModel)]="i.path" name="path{{ index }}" /></td>
                <td><input nz-input [(ngModel)]="i.url" name="url{{ index }}" /></td>
              </tr>
            </tbody>
          </nz-table>
        </div>
      `,
    })
    export class ComponentsZipSaveComponent {
      instance: JSZip | null = null;
      data: { path: string; url: string }[] = [
        { path: 'demo.docx', url: 'https://ng-alain.com/assets/demo.docx' },
        { path: 'img/zorro.svg', url: 'https://ng.ant.design/assets/img/zorro.svg' },
        { path: '小程序标志.zip', url: 'https://wximg.gtimg.com/shake_tv/mina/standard_logo.zip' },
      ];
    
      constructor(private zip: ZipService, private msg: NzMessageService) {
        this.zip.create().then(ret => (this.instance = ret));
      }
    
      add(): void {
        this.data.push({ path: '', url: '' });
      }
    
      download(): void {
        const promises: Promise<void>[] = [];
        this.data.forEach(item => {
          promises.push(this.zip.pushUrl(this.instance, item.path, item.url));
        });
        Promise.all(promises).then(
          () => {
            this.zip.save(this.instance).then(() => {
              this.msg.success('download success');
              this.data = [];
            });
          },
          (error: {}) => {
            console.warn(error);
            this.msg.error(JSON.stringify(error));
          },
        );
      }
    }

    API

    ZipService

    PropertyDescriptionTypeDefault
    read(fileOrUrl: File | string, options?: JSZip.JSZipLoadOptions)DecompressionPromise<JSZip>-
    create()Create a Zip instance for creating a compressed filePromise<JSZip>-
    pushUrl(zip: JSZip, path: string, url: string)Download the URL resource and write it to zipPromise<void>-
    save(zip: JSZip, options?: ZipWriteOptions)SavePromise<void>-