Upload上传
文件选择上传和拖拽上传控件。
何时使用
上传是将信息(网页、文字、图片、视频等)通过网页或者上传工具发布到远程服务器上的过程。
- 当需要上传一个或一些文件时。
- 当需要展现上传的进度时。
- 当需要使用拖拽交互时。
代码演示
经典款式,用户点击按钮弹出文件选择框。
import { Component } from '@angular/core';
@Component({
selector: 'nz-demo-upload-basic',
template: `
<nz-upload nzAction="https://jsonplaceholder.typicode.com/posts/">
<button nz-button><i nz-icon nzType="upload"></i><span>Click to Upload</span></button>
</nz-upload>
`
})
export class NzDemoUploadBasicComponent {}
使用 nzFileList
设置已上传的内容。
import { Component } from '@angular/core';
@Component({
selector: 'nz-demo-upload-file-list',
template: `
<nz-upload nzAction="https://jsonplaceholder.typicode.com/posts/" [nzFileList]="fileList">
<button nz-button><i nz-icon nzType="upload"></i><span>Upload</span></button>
</nz-upload>
`
})
export class NzDemoUploadFileListComponent {
fileList = [
{
uid: 1,
name: 'xxx.png',
status: 'done',
response: 'Server Error 500', // custom error message to show
url: 'http://www.baidu.com/xxx.png'
},
{
uid: 2,
name: 'yyy.png',
status: 'done',
url: 'http://www.baidu.com/yyy.png'
},
{
uid: 3,
name: 'zzz.png',
status: 'error',
response: 'Server Error 500', // custom error message to show
url: 'http://www.baidu.com/zzz.png'
}
];
}
使用 nzFilter
对列表进行完全控制,可以实现各种自定义功能,以下演示三种情况:
1) 上传列表数量的限制。
2) 读取远程路径并显示链接。
3) 按照服务器返回信息筛选成功上传的文件。
import { Component } from '@angular/core';
import { NzMessageService, UploadFile, UploadFilter } from 'ng-zorro-antd';
import { Observable, Observer } from 'rxjs';
@Component({
selector: 'nz-demo-upload-filter',
template: `
<nz-upload
nzAction="https://jsonplaceholder.typicode.com/posts/"
[nzFileList]="fileList"
nzMultiple
[nzLimit]="2"
[nzFilter]="filters"
(nzChange)="handleChange($event)"
>
<button nz-button><i nz-icon nzType="upload"></i><span>Upload</span></button>
</nz-upload>
`
})
export class NzDemoUploadFilterComponent {
constructor(private msg: NzMessageService) {}
filters: UploadFilter[] = [
{
name: 'type',
fn: (fileList: UploadFile[]) => {
const filterFiles = fileList.filter(w => ~['image/png'].indexOf(w.type));
if (filterFiles.length !== fileList.length) {
this.msg.error(`包含文件格式不正确,只支持 png 格式`);
return filterFiles;
}
return fileList;
}
},
{
name: 'async',
fn: (fileList: UploadFile[]) => {
return new Observable((observer: Observer<UploadFile[]>) => {
// doing
observer.next(fileList);
observer.complete();
});
}
}
];
fileList = [
{
uid: -1,
name: 'xxx.png',
status: 'done',
url: 'http://www.baidu.com/xxx.png'
}
];
// tslint:disable-next-line:no-any
handleChange(info: any): void {
const fileList = info.fileList;
// 2. read from response and show file link
if (info.file.response) {
info.file.url = info.file.response.url;
}
// 3. filter successfully uploaded files according to response from server
// tslint:disable-next-line:no-any
this.fileList = fileList.filter((item: any) => {
if (item.response) {
return item.response.status === 'success';
}
return true;
});
}
}
支持上传一个文件夹里的所有文件。
import { Component } from '@angular/core';
@Component({
selector: 'nz-demo-upload-directory',
template: `
<nz-upload nzAction="https://jsonplaceholder.typicode.com/posts/" nzDirectory>
<button nz-button><i nz-icon nzType="upload"></i> Upload Directory</button>
</nz-upload>
`
})
export class NzDemoUploadDirectoryComponent {}
上传文件为图片,可展示本地缩略图。IE8/9
不支持浏览器本地缩略图展示(Ref),可以写 thumbUrl
属性来代替。
import { Component } from '@angular/core';
@Component({
selector: 'nz-demo-upload-picture-style',
template: `
<div class="clearfix">
<nz-upload nzAction="https://jsonplaceholder.typicode.com/posts/" nzListType="picture" [(nzFileList)]="fileList1">
<button nz-button><i nz-icon nzType="upload"></i><span>Upload</span></button>
</nz-upload>
</div>
<br /><br />
<div class="clearfix">
<nz-upload
class="upload-list-inline"
nzAction="https://jsonplaceholder.typicode.com/posts/"
nzListType="picture"
[(nzFileList)]="fileList2"
>
<button nz-button>
<span><i nz-icon nzType="upload"></i> Upload</span>
</button>
</nz-upload>
</div>
`,
styles: [
`
:host ::ng-deep .upload-list-inline .ant-upload-list-item {
float: left;
width: 200px;
margin-right: 8px;
}
`
]
})
export class NzDemoUploadPictureStyleComponent {
defaultFileList = [
{
uid: -1,
name: 'xxx.png',
status: 'done',
url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
thumbUrl: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png'
},
{
uid: -2,
name: 'yyy.png',
status: 'done',
url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
thumbUrl: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png'
}
];
fileList1 = [...this.defaultFileList];
fileList2 = [...this.defaultFileList];
}
点击上传用户头像,并使用 nzBeforeUpload
限制用户上传的图片格式和大小。
nzBeforeUpload
的返回值可以是一个 Observable 以支持也支持异步检查。
import { Component } from '@angular/core';
import { NzMessageService, UploadFile } from 'ng-zorro-antd';
import { Observable, Observer } from 'rxjs';
@Component({
selector: 'nz-demo-upload-avatar',
template: `
<nz-upload
class="avatar-uploader"
nzAction="https://jsonplaceholder.typicode.com/posts/"
nzName="avatar"
nzListType="picture-card"
[nzShowUploadList]="false"
[nzBeforeUpload]="beforeUpload"
(nzChange)="handleChange($event)"
>
<ng-container *ngIf="!avatarUrl">
<i class="upload-icon" nz-icon [nzType]="loading ? 'loading' : 'plus'"></i>
<div class="ant-upload-text">Upload</div>
</ng-container>
<img *ngIf="avatarUrl" [src]="avatarUrl" class="avatar" />
</nz-upload>
`,
styles: [
`
.avatar {
width: 128px;
height: 128px;
}
.upload-icon {
font-size: 32px;
color: #999;
}
.ant-upload-text {
margin-top: 8px;
color: #666;
}
`
]
})
export class NzDemoUploadAvatarComponent {
loading = false;
avatarUrl: string;
constructor(private msg: NzMessageService) {}
beforeUpload = (file: File) => {
return new Observable((observer: Observer<boolean>) => {
const isJPG = file.type === 'image/jpeg';
if (!isJPG) {
this.msg.error('You can only upload JPG file!');
observer.complete();
return;
}
const isLt2M = file.size / 1024 / 1024 < 2;
if (!isLt2M) {
this.msg.error('Image must smaller than 2MB!');
observer.complete();
return;
}
// check height
this.checkImageDimension(file).then(dimensionRes => {
if (!dimensionRes) {
this.msg.error('Image only 300x300 above');
observer.complete();
return;
}
observer.next(isJPG && isLt2M && dimensionRes);
observer.complete();
});
});
};
private getBase64(img: File, callback: (img: string) => void): void {
const reader = new FileReader();
reader.addEventListener('load', () => callback(reader.result!.toString()));
reader.readAsDataURL(img);
}
private checkImageDimension(file: File): Promise<boolean> {
return new Promise(resolve => {
const img = new Image(); // create image
img.src = window.URL.createObjectURL(file);
img.onload = () => {
const width = img.naturalWidth;
const height = img.naturalHeight;
window.URL.revokeObjectURL(img.src!);
resolve(width === height && width >= 300);
};
});
}
handleChange(info: { file: UploadFile }): void {
switch (info.file.status) {
case 'uploading':
this.loading = true;
break;
case 'done':
// Get this url from response in real world.
this.getBase64(info.file!.originFileObj!, (img: string) => {
this.loading = false;
this.avatarUrl = img;
});
break;
case 'error':
this.msg.error('Network error');
this.loading = false;
break;
}
}
}
用户可以上传图片并在列表中显示缩略图。当上传照片数到达限制后,上传按钮消失。
import { Component } from '@angular/core';
import { UploadFile } from 'ng-zorro-antd';
@Component({
selector: 'nz-demo-upload-picture-card',
template: `
<div class="clearfix">
<nz-upload
nzAction="https://jsonplaceholder.typicode.com/posts/"
nzListType="picture-card"
[(nzFileList)]="fileList"
[nzShowButton]="fileList.length < 3"
[nzShowUploadList]="showUploadList"
[nzPreview]="handlePreview"
>
<i nz-icon nzType="plus"></i>
<div class="ant-upload-text">Upload</div>
</nz-upload>
<nz-modal
[nzVisible]="previewVisible"
[nzContent]="modalContent"
[nzFooter]="null"
(nzOnCancel)="previewVisible = false"
>
<ng-template #modalContent>
<img [src]="previewImage" [ngStyle]="{ width: '100%' }" />
</ng-template>
</nz-modal>
</div>
`,
styles: [
`
i[nz-icon] {
font-size: 32px;
color: #999;
}
.ant-upload-text {
margin-top: 8px;
color: #666;
}
`
]
})
export class NzDemoUploadPictureCardComponent {
showUploadList = {
showPreviewIcon: true,
showRemoveIcon: true,
hidePreviewIconInNonImage: true
};
fileList = [
{
uid: -1,
name: 'xxx.png',
status: 'done',
url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png'
}
];
previewImage: string | undefined = '';
previewVisible = false;
constructor() {}
handlePreview = (file: UploadFile) => {
this.previewImage = file.url || file.thumbUrl;
this.previewVisible = true;
};
}
把文件拖入指定区域,完成上传,同样支持点击上传。
设置 nzMultiple
后,在 IE10+
可以一次上传多个文件。
import { Component } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd';
@Component({
selector: 'nz-demo-upload-drag',
template: `
<nz-upload
nzType="drag"
[nzMultiple]="true"
[nzLimit]="2"
nzAction="https://jsonplaceholder.typicode.com/posts/"
(nzChange)="handleChange($event)"
>
<p class="ant-upload-drag-icon">
<i nz-icon nzType="inbox"></i>
</p>
<p class="ant-upload-text">Click or drag file to this area to upload</p>
<p class="ant-upload-hint">
Support for a single or bulk upload. Strictly prohibit from uploading company data or other band files
</p>
</nz-upload>
`
})
export class NzDemoUploadDragComponent {
constructor(private msg: NzMessageService) {}
// tslint:disable-next-line:no-any
handleChange({ file, fileList }: { [key: string]: any }): void {
const status = file.status;
if (status !== 'uploading') {
console.log(file, fileList);
}
if (status === 'done') {
this.msg.success(`${file.name} file uploaded successfully.`);
} else if (status === 'error') {
this.msg.error(`${file.name} file upload failed.`);
}
}
}
nzBeforeUpload
返回 false
后,手动上传文件。
import { HttpClient, HttpRequest, HttpResponse } from '@angular/common/http';
import { Component } from '@angular/core';
import { NzMessageService, UploadFile } from 'ng-zorro-antd';
import { filter } from 'rxjs/operators';
@Component({
selector: 'nz-demo-upload-manually',
template: `
<nz-upload [(nzFileList)]="fileList" [nzBeforeUpload]="beforeUpload">
<button nz-button><i nz-icon nzType="upload"></i><span>Select File</span></button>
</nz-upload>
<button
nz-button
[nzType]="'primary'"
[nzLoading]="uploading"
(click)="handleUpload()"
[disabled]="fileList.length == 0"
style="margin-top: 16px"
>
{{ uploading ? 'Uploading' : 'Start Upload' }}
</button>
`
})
export class NzDemoUploadManuallyComponent {
uploading = false;
fileList: UploadFile[] = [];
constructor(private http: HttpClient, private msg: NzMessageService) {}
beforeUpload = (file: UploadFile): boolean => {
this.fileList = this.fileList.concat(file);
return false;
};
handleUpload(): void {
const formData = new FormData();
// tslint:disable-next-line:no-any
this.fileList.forEach((file: any) => {
formData.append('files[]', file);
});
this.uploading = true;
// You can use any AJAX library you like
const req = new HttpRequest('POST', 'https://jsonplaceholder.typicode.com/posts/', formData, {
// reportProgress: true
});
this.http
.request(req)
.pipe(filter(e => e instanceof HttpResponse))
.subscribe(
() => {
this.uploading = false;
this.fileList = [];
this.msg.success('upload successfully.');
},
() => {
this.uploading = false;
this.msg.error('upload failed.');
}
);
}
}
使用 nzCustomRequest
改变上传行为。
import { HttpClient, HttpEvent, HttpEventType, HttpRequest, HttpResponse } from '@angular/common/http';
import { Component } from '@angular/core';
import { UploadXHRArgs } from 'ng-zorro-antd';
import { forkJoin } from 'rxjs';
@Component({
selector: 'nz-demo-upload-custom-request',
template: `
<nz-upload nzAction="https://jsonplaceholder.typicode.com/posts/" [nzCustomRequest]="customReq">
<button nz-button><i nz-icon nzType="upload"></i><span>Click to Upload</span></button>
</nz-upload>
`
})
export class NzDemoUploadCustomRequestComponent {
constructor(private http: HttpClient) {}
customReq = (item: UploadXHRArgs) => {
// 构建一个 FormData 对象,用于存储文件或其他参数
const formData = new FormData();
// tslint:disable-next-line:no-any
formData.append('file', item.file as any);
formData.append('id', '1000');
const req = new HttpRequest('POST', item.action!, formData, {
reportProgress: true,
withCredentials: true
});
// 始终返回一个 `Subscription` 对象,nz-upload 会在适当时机自动取消订阅
return this.http.request(req).subscribe(
(event: HttpEvent<{}>) => {
if (event.type === HttpEventType.UploadProgress) {
if (event.total! > 0) {
// tslint:disable-next-line:no-any
(event as any).percent = (event.loaded / event.total!) * 100;
}
// 处理上传进度条,必须指定 `percent` 属性来表示进度
item.onProgress!(event, item.file!);
} else if (event instanceof HttpResponse) {
// 处理成功
item.onSuccess!(event.body, item.file!, event);
}
},
err => {
// 处理失败
item.onError!(err, item.file!);
}
);
};
// 一个简单的分片上传
customBigReq = (item: UploadXHRArgs) => {
const size = item.file.size;
const chunkSize = parseInt(size / 3 + '', 10);
const maxChunk = Math.ceil(size / chunkSize);
const reqs = Array(maxChunk)
.fill(0)
.map((_: {}, index: number) => {
const start = index * chunkSize;
let end = start + chunkSize;
if (size - end < 0) {
end = size;
}
const formData = new FormData();
formData.append('file', item.file.slice(start, end));
formData.append('start', start.toString());
formData.append('end', end.toString());
formData.append('index', index.toString());
const req = new HttpRequest('POST', item.action!, formData, {
withCredentials: true
});
return this.http.request(req);
});
return forkJoin(...reqs).subscribe(
() => {
// 处理成功
item.onSuccess!({}, item.file!, event);
},
err => {
// 处理失败
item.onError!(err, item.file!);
}
);
};
}
API
服务端上传接口实现可以参考 jQuery-File-Upload。
单独引入此组件
想要了解更多关于单独引入组件的内容,可以在快速上手页面进行查看。
import { NzUploadModule } from 'ng-zorro-antd';
nz-uploadcomponent
参数 | 说明 | 类型 | 默认值 |
---|---|---|---|
[nzAccept] | 接受上传的文件类型, 详见 input accept Attribute | string | - |
[nzAction] | 必选参数, 上传的地址 | string | - |
[nzDirectory] | 支持上传文件夹(caniuse) | boolean | false |
[nzBeforeUpload] | 上传文件之前的钩子,参数为上传的文件,若返回 false 则停止上传。注意:IE9 不支持该方法;注意:务必使用 => 定义处理方法。 | (file: UploadFile, fileList: UploadFile[]) => boolean|Observable<boolean> | - |
[nzCustomRequest] | 通过覆盖默认的上传行为,可以自定义自己的上传实现;注意:务必使用 => 定义处理方法。 | (item) => Subscription | - |
[nzData] | 上传所需参数或返回上传参数的方法;注意:务必使用 => 定义处理方法。 | Object|((file: UploadFile) => Object) | - |
[nzDisabled] | 是否禁用 | boolean | false |
[nzFileList] | 文件列表,双向绑定 | UploadFile[] | - |
[nzLimit] | 限制单次最多上传数量,nzMultiple 打开时有效;0 表示不限 | number | 0 |
[nzSize] | 限制文件大小,单位:KB;0 表示不限 | number | 0 |
[nzFileType] | 限制文件类型,例如:image/png,image/jpeg,image/gif,image/bmp | string | - |
[nzFilter] | 自定义过滤器 | UploadFilter[] | - |
[nzHeaders] | 设置上传的请求头部,IE10 以上有效;注意:务必使用 => 定义处理方法。 | Object|((file: UploadFile) => Object) | - |
[nzListType] | 上传列表的内建样式,支持三种基本样式 text , picture 和 picture-card | 'text'|'picture'|'picture-card' | 'text' |
[nzMultiple] | 是否支持多选文件,ie10+ 支持。开启后按住 ctrl 可选择多个文件。 | boolean | false |
[nzName] | 发到后台的文件参数名 | string | 'file' |
[nzShowUploadList] | 是否展示 uploadList, 可设为一个对象,用于单独设定 showPreviewIcon 和 showRemoveIcon | boolean|{ showPreviewIcon?: boolean, showRemoveIcon?: boolean } | true |
[nzShowButton] | 是否展示上传按钮 | boolean | true |
[nzWithCredentials] | 上传请求时是否携带 cookie | boolean | false |
[nzOpenFileDialogOnClick] | 点击打开文件对话框 | boolean | true |
[nzPreview] | 点击文件链接或预览图标时的回调;注意:务必使用 => 定义处理方法。 | (file: UploadFile) => void | - |
[nzRemove] | 点击移除文件时的回调,返回值为 false 时不移除。支持返回 Observable 对象;注意:务必使用 => 定义处理方法。 | (file: UploadFile) => boolean|Observable<boolean> | - |
(nzChange) | 上传文件改变时的状态 | EventEmitter<UploadChangeParam> | - |
nzChange
开始、上传进度、完成、失败都会调用这个函数。
文件状态改变的回调,返回为:
{
file: { /* ... */ },
fileList: [ /* ... */ ],
event: { /* ... */ },
}
file
当前操作的文件对象。
{
uid: 'uid', // 文件唯一标识
name: 'xx.png' // 文件名
status: 'done', // 状态有:uploading done error removed
response: '{"status": "success"}', // 服务端响应内容
linkProps: '{"download": "image"}', // 下载链接额外的 HTML 属性
}
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