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

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

Upload上传 - 图7

照片墙

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

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

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';
  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. // 构建一个 FormData 对象,用于存储文件或其他参数
  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. // 始终返回一个 `Subscription` 对象,nz-upload 会在适当时机自动取消订阅
  26. return this.http.request(req).subscribe(
  27. (event: HttpEvent<{}>) => {
  28. if (event.type === HttpEventType.UploadProgress) {
  29. if (event.total! > 0) {
  30. // tslint:disable-next-line:no-any
  31. (event as any).percent = (event.loaded / event.total!) * 100;
  32. }
  33. // 处理上传进度条,必须指定 `percent` 属性来表示进度
  34. item.onProgress!(event, item.file!);
  35. } else if (event instanceof HttpResponse) {
  36. // 处理成功
  37. item.onSuccess!(event.body, item.file!, event);
  38. }
  39. },
  40. err => {
  41. // 处理失败
  42. item.onError!(err, item.file!);
  43. }
  44. );
  45. };
  46. // 一个简单的分片上传
  47. customBigReq = (item: UploadXHRArgs) => {
  48. const size = item.file.size;
  49. const chunkSize = parseInt(size / 3 + '', 10);
  50. const maxChunk = Math.ceil(size / chunkSize);
  51. const reqs = Array(maxChunk)
  52. .fill(0)
  53. .map((_: {}, index: number) => {
  54. const start = index * chunkSize;
  55. let end = start + chunkSize;
  56. if (size - end < 0) {
  57. end = size;
  58. }
  59. const formData = new FormData();
  60. formData.append('file', item.file.slice(start, end));
  61. formData.append('start', start.toString());
  62. formData.append('end', end.toString());
  63. formData.append('index', index.toString());
  64. const req = new HttpRequest('POST', item.action!, formData, {
  65. withCredentials: true
  66. });
  67. return this.http.request(req);
  68. });
  69. return forkJoin(...reqs).subscribe(
  70. () => {
  71. // 处理成功
  72. item.onSuccess!({}, item.file!, event);
  73. },
  74. err => {
  75. // 处理失败
  76. item.onError!(err, item.file!);
  77. }
  78. );
  79. };
  80. }

API

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

单独引入此组件

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

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

nz-uploadcomponent

参数说明类型默认值
[nzAccept]接受上传的文件类型, 详见 input accept Attributestring-
[nzAction]必选参数, 上传的地址string-
[nzDirectory]支持上传文件夹(caniusebooleanfalse
[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