• Upload上传
    • 何时使用
    • 单独引入此组件
    • 代码演示
    • API
      • nz-uploadcomponent
        • nzChange
        • nzCustomRequest

    Upload上传

    文件选择上传和拖拽上传控件。

    何时使用

    上传是将信息(网页、文字、图片、视频等)通过网页或者上传工具发布到远程服务器上的过程。

    • 当需要上传一个或一些文件时。
    • 当需要展现上传的进度时。
    • 当需要使用拖拽交互时。

    单独引入此组件

    想要了解更多关于单独引入组件的内容,可以在快速上手页面进行查看。

    1. import { NzUploadModule } from 'ng-zorro-antd/upload';

    代码演示

    Upload上传 - 图1

    点击上传

    经典款式,用户点击按钮弹出文件选择框。

    1. import { Component } from '@angular/core';
    2. @Component({
    3. selector: 'nz-demo-upload-basic',
    4. template: `
    5. <nz-upload nzAction="https://jsonplaceholder.typicode.com/posts/">
    6. <button nz-button><i nz-icon nzType="upload"></i><span>Click to Upload</span></button>
    7. </nz-upload>
    8. `
    9. })
    10. export class NzDemoUploadBasicComponent {}

    Upload上传 - 图2

    已上传的文件列表

    使用 nzFileList 设置已上传的内容。

    1. import { Component } from '@angular/core';
    2. @Component({
    3. selector: 'nz-demo-upload-file-list',
    4. template: `
    5. <nz-upload nzAction="https://jsonplaceholder.typicode.com/posts/" [nzFileList]="fileList">
    6. <button nz-button><i nz-icon nzType="upload"></i><span>Upload</span></button>
    7. </nz-upload>
    8. `
    9. })
    10. export class NzDemoUploadFileListComponent {
    11. fileList = [
    12. {
    13. uid: 1,
    14. name: 'xxx.png',
    15. status: 'done',
    16. response: 'Server Error 500', // custom error message to show
    17. url: 'http://www.baidu.com/xxx.png'
    18. },
    19. {
    20. uid: 2,
    21. name: 'yyy.png',
    22. status: 'done',
    23. url: 'http://www.baidu.com/yyy.png'
    24. },
    25. {
    26. uid: 3,
    27. name: 'zzz.png',
    28. status: 'error',
    29. response: 'Server Error 500', // custom error message to show
    30. url: 'http://www.baidu.com/zzz.png'
    31. }
    32. ];
    33. }

    Upload上传 - 图3

    过滤器

    使用 nzFilter 对列表进行完全控制,可以实现各种自定义功能,以下演示三种情况:

    1) 上传列表数量的限制。

    2) 读取远程路径并显示链接。

    3) 按照服务器返回信息筛选成功上传的文件。

    1. import { Component } from '@angular/core';
    2. import { NzMessageService } from 'ng-zorro-antd/message';
    3. import { UploadFile, UploadFilter } from 'ng-zorro-antd/upload';
    4. import { Observable, Observer } from 'rxjs';
    5. @Component({
    6. selector: 'nz-demo-upload-filter',
    7. template: `
    8. <nz-upload
    9. nzAction="https://jsonplaceholder.typicode.com/posts/"
    10. [nzFileList]="fileList"
    11. nzMultiple
    12. [nzLimit]="2"
    13. [nzFilter]="filters"
    14. (nzChange)="handleChange($event)"
    15. >
    16. <button nz-button><i nz-icon nzType="upload"></i><span>Upload</span></button>
    17. </nz-upload>
    18. `
    19. })
    20. export class NzDemoUploadFilterComponent {
    21. constructor(private msg: NzMessageService) {}
    22. filters: UploadFilter[] = [
    23. {
    24. name: 'type',
    25. fn: (fileList: UploadFile[]) => {
    26. const filterFiles = fileList.filter(w => ~['image/png'].indexOf(w.type));
    27. if (filterFiles.length !== fileList.length) {
    28. this.msg.error(`包含文件格式不正确,只支持 png 格式`);
    29. return filterFiles;
    30. }
    31. return fileList;
    32. }
    33. },
    34. {
    35. name: 'async',
    36. fn: (fileList: UploadFile[]) => {
    37. return new Observable((observer: Observer<UploadFile[]>) => {
    38. // doing
    39. observer.next(fileList);
    40. observer.complete();
    41. });
    42. }
    43. }
    44. ];
    45. fileList = [
    46. {
    47. uid: -1,
    48. name: 'xxx.png',
    49. status: 'done',
    50. url: 'http://www.baidu.com/xxx.png'
    51. }
    52. ];
    53. // tslint:disable-next-line:no-any
    54. handleChange(info: any): void {
    55. const fileList = info.fileList;
    56. // 2. read from response and show file link
    57. if (info.file.response) {
    58. info.file.url = info.file.response.url;
    59. }
    60. // 3. filter successfully uploaded files according to response from server
    61. // tslint:disable-next-line:no-any
    62. this.fileList = fileList.filter((item: any) => {
    63. if (item.response) {
    64. return item.response.status === 'success';
    65. }
    66. return true;
    67. });
    68. }
    69. }

    Upload上传 - 图4

    文件夹上传

    支持上传一个文件夹里的所有文件。

    1. import { Component } from '@angular/core';
    2. @Component({
    3. selector: 'nz-demo-upload-directory',
    4. template: `
    5. <nz-upload nzAction="https://jsonplaceholder.typicode.com/posts/" nzDirectory>
    6. <button nz-button><i nz-icon nzType="upload"></i> Upload Directory</button>
    7. </nz-upload>
    8. `
    9. })
    10. export class NzDemoUploadDirectoryComponent {}

    Upload上传 - 图5

    图片列表样式

    上传文件为图片,可展示本地缩略图。IE8/9 不支持浏览器本地缩略图展示(Ref),可以写 thumbUrl 属性来代替。

    1. import { Component } from '@angular/core';
    2. @Component({
    3. selector: 'nz-demo-upload-picture-style',
    4. template: `
    5. <div class="clearfix">
    6. <nz-upload nzAction="https://jsonplaceholder.typicode.com/posts/" nzListType="picture" [(nzFileList)]="fileList1">
    7. <button nz-button><i nz-icon nzType="upload"></i><span>Upload</span></button>
    8. </nz-upload>
    9. </div>
    10. <br /><br />
    11. <div class="clearfix">
    12. <nz-upload
    13. class="upload-list-inline"
    14. nzAction="https://jsonplaceholder.typicode.com/posts/"
    15. nzListType="picture"
    16. [(nzFileList)]="fileList2"
    17. >
    18. <button nz-button>
    19. <span><i nz-icon nzType="upload"></i> Upload</span>
    20. </button>
    21. </nz-upload>
    22. </div>
    23. `,
    24. styles: [
    25. `
    26. :host ::ng-deep .upload-list-inline .ant-upload-list-item {
    27. float: left;
    28. width: 200px;
    29. margin-right: 8px;
    30. }
    31. `
    32. ]
    33. })
    34. export class NzDemoUploadPictureStyleComponent {
    35. defaultFileList = [
    36. {
    37. uid: -1,
    38. name: 'xxx.png',
    39. status: 'done',
    40. url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
    41. thumbUrl: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png'
    42. },
    43. {
    44. uid: -2,
    45. name: 'yyy.png',
    46. status: 'done',
    47. url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
    48. thumbUrl: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png'
    49. }
    50. ];
    51. fileList1 = [...this.defaultFileList];
    52. fileList2 = [...this.defaultFileList];
    53. }

    Upload上传 - 图6

    用户头像

    点击上传用户头像,并使用 nzBeforeUpload 限制用户上传的图片格式和大小。

    nzBeforeUpload 的返回值可以是一个 Observable 以支持也支持异步检查。

    1. import { Component } from '@angular/core';
    2. import { NzMessageService } from 'ng-zorro-antd/message';
    3. import { UploadFile } from 'ng-zorro-antd/upload';
    4. import { Observable, Observer } from 'rxjs';
    5. @Component({
    6. selector: 'nz-demo-upload-avatar',
    7. template: `
    8. <nz-upload
    9. class="avatar-uploader"
    10. nzAction="https://jsonplaceholder.typicode.com/posts/"
    11. nzName="avatar"
    12. nzListType="picture-card"
    13. [nzShowUploadList]="false"
    14. [nzBeforeUpload]="beforeUpload"
    15. (nzChange)="handleChange($event)"
    16. >
    17. <ng-container *ngIf="!avatarUrl">
    18. <i class="upload-icon" nz-icon [nzType]="loading ? 'loading' : 'plus'"></i>
    19. <div class="ant-upload-text">Upload</div>
    20. </ng-container>
    21. <img *ngIf="avatarUrl" [src]="avatarUrl" class="avatar" />
    22. </nz-upload>
    23. `,
    24. styles: [
    25. `
    26. .avatar {
    27. width: 128px;
    28. height: 128px;
    29. }
    30. .upload-icon {
    31. font-size: 32px;
    32. color: #999;
    33. }
    34. .ant-upload-text {
    35. margin-top: 8px;
    36. color: #666;
    37. }
    38. `
    39. ]
    40. })
    41. export class NzDemoUploadAvatarComponent {
    42. loading = false;
    43. avatarUrl: string;
    44. constructor(private msg: NzMessageService) {}
    45. beforeUpload = (file: File) => {
    46. return new Observable((observer: Observer<boolean>) => {
    47. const isJPG = file.type === 'image/jpeg';
    48. if (!isJPG) {
    49. this.msg.error('You can only upload JPG file!');
    50. observer.complete();
    51. return;
    52. }
    53. const isLt2M = file.size / 1024 / 1024 < 2;
    54. if (!isLt2M) {
    55. this.msg.error('Image must smaller than 2MB!');
    56. observer.complete();
    57. return;
    58. }
    59. // check height
    60. this.checkImageDimension(file).then(dimensionRes => {
    61. if (!dimensionRes) {
    62. this.msg.error('Image only 300x300 above');
    63. observer.complete();
    64. return;
    65. }
    66. observer.next(isJPG && isLt2M && dimensionRes);
    67. observer.complete();
    68. });
    69. });
    70. };
    71. private getBase64(img: File, callback: (img: string) => void): void {
    72. const reader = new FileReader();
    73. reader.addEventListener('load', () => callback(reader.result!.toString()));
    74. reader.readAsDataURL(img);
    75. }
    76. private checkImageDimension(file: File): Promise<boolean> {
    77. return new Promise(resolve => {
    78. const img = new Image(); // create image
    79. img.src = window.URL.createObjectURL(file);
    80. img.onload = () => {
    81. const width = img.naturalWidth;
    82. const height = img.naturalHeight;
    83. window.URL.revokeObjectURL(img.src!);
    84. resolve(width === height && width >= 300);
    85. };
    86. });
    87. }
    88. handleChange(info: { file: UploadFile }): void {
    89. switch (info.file.status) {
    90. case 'uploading':
    91. this.loading = true;
    92. break;
    93. case 'done':
    94. // Get this url from response in real world.
    95. this.getBase64(info.file!.originFileObj!, (img: string) => {
    96. this.loading = false;
    97. this.avatarUrl = img;
    98. });
    99. break;
    100. case 'error':
    101. this.msg.error('Network error');
    102. this.loading = false;
    103. break;
    104. }
    105. }
    106. }

    Upload上传 - 图7

    照片墙

    用户可以上传图片并在列表中显示缩略图。当上传照片数到达限制后,上传按钮消失。

    1. import { Component } from '@angular/core';
    2. import { UploadFile } from 'ng-zorro-antd/upload';
    3. @Component({
    4. selector: 'nz-demo-upload-picture-card',
    5. template: `
    6. <div class="clearfix">
    7. <nz-upload
    8. nzAction="https://jsonplaceholder.typicode.com/posts/"
    9. nzListType="picture-card"
    10. [(nzFileList)]="fileList"
    11. [nzShowButton]="fileList.length < 3"
    12. [nzShowUploadList]="showUploadList"
    13. [nzPreview]="handlePreview"
    14. >
    15. <i nz-icon nzType="plus"></i>
    16. <div class="ant-upload-text">Upload</div>
    17. </nz-upload>
    18. <nz-modal
    19. [nzVisible]="previewVisible"
    20. [nzContent]="modalContent"
    21. [nzFooter]="null"
    22. (nzOnCancel)="previewVisible = false"
    23. >
    24. <ng-template #modalContent>
    25. <img [src]="previewImage" [ngStyle]="{ width: '100%' }" />
    26. </ng-template>
    27. </nz-modal>
    28. </div>
    29. `,
    30. styles: [
    31. `
    32. i[nz-icon] {
    33. font-size: 32px;
    34. color: #999;
    35. }
    36. .ant-upload-text {
    37. margin-top: 8px;
    38. color: #666;
    39. }
    40. `
    41. ]
    42. })
    43. export class NzDemoUploadPictureCardComponent {
    44. showUploadList = {
    45. showPreviewIcon: true,
    46. showRemoveIcon: true,
    47. hidePreviewIconInNonImage: true
    48. };
    49. fileList = [
    50. {
    51. uid: -1,
    52. name: 'xxx.png',
    53. status: 'done',
    54. url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png'
    55. }
    56. ];
    57. previewImage: string | undefined = '';
    58. previewVisible = false;
    59. constructor() {}
    60. handlePreview = (file: UploadFile) => {
    61. this.previewImage = file.url || file.thumbUrl;
    62. this.previewVisible = true;
    63. };
    64. }

    Upload上传 - 图8

    拖拽上传

    把文件拖入指定区域,完成上传,同样支持点击上传。

    设置 nzMultiple 后,在 IE10+ 可以一次上传多个文件。

    1. import { Component } from '@angular/core';
    2. import { NzMessageService } from 'ng-zorro-antd/message';
    3. @Component({
    4. selector: 'nz-demo-upload-drag',
    5. template: `
    6. <nz-upload
    7. nzType="drag"
    8. [nzMultiple]="true"
    9. [nzLimit]="2"
    10. nzAction="https://jsonplaceholder.typicode.com/posts/"
    11. (nzChange)="handleChange($event)"
    12. >
    13. <p class="ant-upload-drag-icon">
    14. <i nz-icon nzType="inbox"></i>
    15. </p>
    16. <p class="ant-upload-text">Click or drag file to this area to upload</p>
    17. <p class="ant-upload-hint">
    18. Support for a single or bulk upload. Strictly prohibit from uploading company data or other band files
    19. </p>
    20. </nz-upload>
    21. `
    22. })
    23. export class NzDemoUploadDragComponent {
    24. constructor(private msg: NzMessageService) {}
    25. // tslint:disable-next-line:no-any
    26. handleChange({ file, fileList }: { [key: string]: any }): void {
    27. const status = file.status;
    28. if (status !== 'uploading') {
    29. console.log(file, fileList);
    30. }
    31. if (status === 'done') {
    32. this.msg.success(`${file.name} file uploaded successfully.`);
    33. } else if (status === 'error') {
    34. this.msg.error(`${file.name} file upload failed.`);
    35. }
    36. }
    37. }

    Upload上传 - 图9

    手动上传

    nzBeforeUpload 返回 false 后,手动上传文件。

    1. import { HttpClient, HttpRequest, HttpResponse } from '@angular/common/http';
    2. import { Component } from '@angular/core';
    3. import { NzMessageService } from 'ng-zorro-antd/message';
    4. import { UploadFile } from 'ng-zorro-antd/upload';
    5. import { filter } from 'rxjs/operators';
    6. @Component({
    7. selector: 'nz-demo-upload-manually',
    8. template: `
    9. <nz-upload [(nzFileList)]="fileList" [nzBeforeUpload]="beforeUpload">
    10. <button nz-button><i nz-icon nzType="upload"></i><span>Select File</span></button>
    11. </nz-upload>
    12. <button
    13. nz-button
    14. [nzType]="'primary'"
    15. [nzLoading]="uploading"
    16. (click)="handleUpload()"
    17. [disabled]="fileList.length == 0"
    18. style="margin-top: 16px"
    19. >
    20. {{ uploading ? 'Uploading' : 'Start Upload' }}
    21. </button>
    22. `
    23. })
    24. export class NzDemoUploadManuallyComponent {
    25. uploading = false;
    26. fileList: UploadFile[] = [];
    27. constructor(private http: HttpClient, private msg: NzMessageService) {}
    28. beforeUpload = (file: UploadFile): boolean => {
    29. this.fileList = this.fileList.concat(file);
    30. return false;
    31. };
    32. handleUpload(): void {
    33. const formData = new FormData();
    34. // tslint:disable-next-line:no-any
    35. this.fileList.forEach((file: any) => {
    36. formData.append('files[]', file);
    37. });
    38. this.uploading = true;
    39. // You can use any AJAX library you like
    40. const req = new HttpRequest('POST', 'https://jsonplaceholder.typicode.com/posts/', formData, {
    41. // reportProgress: true
    42. });
    43. this.http
    44. .request(req)
    45. .pipe(filter(e => e instanceof HttpResponse))
    46. .subscribe(
    47. () => {
    48. this.uploading = false;
    49. this.fileList = [];
    50. this.msg.success('upload successfully.');
    51. },
    52. () => {
    53. this.uploading = false;
    54. this.msg.error('upload failed.');
    55. }
    56. );
    57. }
    58. }

    Upload上传 - 图10

    自定义上传

    使用 nzCustomRequest 改变上传行为。

    1. import { HttpClient, HttpEvent, HttpEventType, HttpRequest, HttpResponse } from '@angular/common/http';
    2. import { Component } from '@angular/core';
    3. import { UploadXHRArgs } from 'ng-zorro-antd/upload';
    4. import { forkJoin } from 'rxjs';
    5. @Component({
    6. selector: 'nz-demo-upload-custom-request',
    7. template: `
    8. <nz-upload nzAction="https://jsonplaceholder.typicode.com/posts/" [nzCustomRequest]="customReq">
    9. <button nz-button><i nz-icon nzType="upload"></i><span>Click to Upload</span></button>
    10. </nz-upload>
    11. `
    12. })
    13. export class NzDemoUploadCustomRequestComponent {
    14. constructor(private http: HttpClient) {}
    15. customReq = (item: UploadXHRArgs) => {
    16. // Create a FormData here to store files and other parameters.
    17. const formData = new FormData();
    18. // tslint:disable-next-line:no-any
    19. formData.append('file', item.file as any);
    20. formData.append('id', '1000');
    21. const req = new HttpRequest('POST', item.action!, formData, {
    22. reportProgress: true,
    23. withCredentials: true
    24. });
    25. // Always returns a `Subscription` object. nz-upload would automatically unsubscribe it at correct time.
    26. return this.http.request(req).subscribe(
    27. // tslint:disable-next-line no-any
    28. (event: HttpEvent<any>) => {
    29. if (event.type === HttpEventType.UploadProgress) {
    30. if (event.total! > 0) {
    31. // tslint:disable-next-line:no-any
    32. (event as any).percent = (event.loaded / event.total!) * 100;
    33. }
    34. item.onProgress!(event, item.file!);
    35. } else if (event instanceof HttpResponse) {
    36. item.onSuccess!(event.body, item.file!, event);
    37. }
    38. },
    39. err => {
    40. item.onError!(err, item.file!);
    41. }
    42. );
    43. };
    44. // A simple sliced upload.
    45. customBigReq = (item: UploadXHRArgs) => {
    46. const size = item.file.size;
    47. const chunkSize = parseInt(size / 3 + '', 10);
    48. const maxChunk = Math.ceil(size / chunkSize);
    49. const reqs = Array(maxChunk)
    50. .fill(0)
    51. .map((_: {}, index: number) => {
    52. const start = index * chunkSize;
    53. let end = start + chunkSize;
    54. if (size - end < 0) {
    55. end = size;
    56. }
    57. const formData = new FormData();
    58. formData.append('file', item.file.slice(start, end));
    59. formData.append('start', start.toString());
    60. formData.append('end', end.toString());
    61. formData.append('index', index.toString());
    62. const req = new HttpRequest('POST', item.action!, formData, {
    63. withCredentials: true
    64. });
    65. return this.http.request(req);
    66. });
    67. return forkJoin(...reqs).subscribe(
    68. () => {
    69. item.onSuccess!({}, item.file!, event);
    70. },
    71. err => {
    72. item.onError!(err, item.file!);
    73. }
    74. );
    75. };
    76. }

    API

    服务端上传接口实现可以参考 jQuery-File-Upload。

    nz-uploadcomponent

    参数说明类型默认值
    [nzAccept]接受上传的文件类型, 详见 input accept Attributestring-
    [nzAction]必选参数, 上传的地址string-
    [nzDirectory]支持上传文件夹(caniuse)booleanfalse
    [nzBeforeUpload]上传文件之前的钩子,参数为上传的文件,若返回 false 则停止上传。注意:IE9 不支持该方法;注意:务必使用 => 定义处理方法。(file: UploadFile, fileList: UploadFile[]) => boolean | Observable<boolean>-
    [nzCustomRequest]通过覆盖默认的上传行为,可以自定义自己的上传实现;注意:务必使用 => 定义处理方法。(item) => Subscription-
    [nzData]上传所需参数或返回上传参数的方法;注意:务必使用 => 定义处理方法。Object | ((file: UploadFile) => Object)-
    [nzDisabled]是否禁用booleanfalse
    [nzFileList]文件列表,双向绑定UploadFile[]-
    [nzLimit]限制单次最多上传数量,nzMultiple 打开时有效;0 表示不限number0
    [nzSize]限制文件大小,单位:KB;0 表示不限number0
    [nzFileType]限制文件类型,例如:image/png,image/jpeg,image/gif,image/bmpstring-
    [nzFilter]自定义过滤器UploadFilter[]-
    [nzHeaders]设置上传的请求头部,IE10 以上有效;注意:务必使用 => 定义处理方法。Object | ((file: UploadFile) => Object)-
    [nzListType]上传列表的内建样式,支持三种基本样式 text, picturepicture-card'text' | 'picture' | 'picture-card''text'
    [nzMultiple]是否支持多选文件,ie10+ 支持。开启后按住 ctrl 可选择多个文件。booleanfalse
    [nzName]发到后台的文件参数名string'file'
    [nzShowUploadList]是否展示 uploadList, 可设为一个对象,用于单独设定 showPreviewIcon 和 showRemoveIconboolean | { showPreviewIcon?: boolean, showRemoveIcon?: boolean }true
    [nzShowButton]是否展示上传按钮booleantrue
    [nzWithCredentials]上传请求时是否携带 cookiebooleanfalse
    [nzOpenFileDialogOnClick]点击打开文件对话框booleantrue
    [nzPreview]点击文件链接或预览图标时的回调;注意:务必使用 => 定义处理方法。(file: UploadFile) => void-
    [nzRemove]点击移除文件时的回调,返回值为 false 时不移除。支持返回 Observable 对象;注意:务必使用 => 定义处理方法。(file: UploadFile) => boolean | Observable<boolean>-
    (nzChange)上传文件改变时的状态EventEmitter<UploadChangeParam>-

    nzChange

    开始、上传进度、完成、失败都会调用这个函数。

    文件状态改变的回调,返回为:

    1. {
    2. file: { /* ... */ },
    3. fileList: [ /* ... */ ],
    4. event: { /* ... */ },
    5. }
    • file 当前操作的文件对象。
    1. {
    2. uid: 'uid', // 文件唯一标识
    3. name: 'xx.png' // 文件名
    4. status: 'done', // 状态有:uploading done error removed
    5. response: '{"status": "success"}', // 服务端响应内容
    6. linkProps: '{"download": "image"}', // 下载链接额外的 HTML 属性
    7. }
    • fileList 当前的文件列表。

    • event 上传中的服务端响应内容,包含了上传进度等信息,高级浏览器支持。

    nzCustomRequest

    默认使用HTML5方式上传(即:使用 HttpClient),允许覆盖默认行为实现定制需求,例如直接与阿里云交互等。

    nzCustomRequest 回调传递以下参数:

    • onProgress: (event: { percent: number }): void
    • onError: (event: Error): void
    • onSuccess: (body: Object, xhr?: Object): void
    • data: Object
    • filename: String
    • file: File
    • withCredentials: Boolean
    • action: String
    • headers: Object