Search code examples
angularng-zorro-antd

How to show file preview if calling nzBeforeUpload=false?


How to show file preview if calling nzBeforeUpload=false?

<nz-upload [nzShowButton]="fileList.length == 0" nzListType="picture-card" [nzBeforeUpload]="beforeUpload" [(nzFileList)]="fileList">
      <div>
        <i nz-icon nzType="plus"></i>
        <div style="margin-top: 8px">Upload</div>
      </div>
</nz-upload>

It works if returning True, but it POSTs file to current url.


Solution

  • I just did:

    <nz-upload [nzShowButton]="fileList.length == 0" [nzIconRender]="test" nzListType="picture-card" [nzBeforeUpload]="beforeUpload"
              [(nzFileList)]="fileList">
              <div>
                <i nz-icon nzType="plus"></i>
                <div>Upload</div>
              </div>
            </nz-upload>
            <ng-template #test><img width=100 height=100 [src]="preview"/></ng-template>
    
      beforeUpload = (file: NzUploadFile): boolean => {
        this.getBase64(file as any).then(x => this.preview=x?.toString() as any)
        this.fileList = this.fileList.concat(file);
        return false;
      }
    
      getBase64(file: File): Promise<string | ArrayBuffer | null> {
        return new Promise((resolve, reject) => {
          const reader = new FileReader();
          reader.readAsDataURL(file);
          reader.onload = () => resolve(reader.result);
          reader.onerror = error => reject(error);
        });
      }