Upload上传
上传是将信息(网页、文字、图片、视频等)通过网页或者上传工具发布到远程服务器上的过程。
- 当需要上传一个或一些文件时。
- 当需要展现上传的进度时。
- 当需要使用拖拽交互时。
点击上传
经典款式,用户点击按钮弹出文件选择框。
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzUploadChangeParam } from 'ng-zorro-antd/upload';
@Component({
selector: 'nz-demo-upload-basic',
template: `
<nz-upload
nzAction="https://www.mocky.io/v2/5cc8019d300000980a055e76"
[nzHeaders]="{ authorization: 'authorization-text' }"
(nzChange)="handleChange($event)"
>
<button nz-button><i nz-icon nzType="upload"></i>Click to Upload</button>
</nz-upload>
`
})
export class NzDemoUploadBasicComponent {
constructor(private msg: NzMessageService) {}
handleChange(info: NzUploadChangeParam): void {
if (info.file.status !== 'uploading') {
console.log(info.file, info.fileList);
}
if (info.file.status === 'done') {
this.msg.success(`${info.file.name} file uploaded successfully`);
} else if (info.file.status === 'error') {
this.msg.error(`${info.file.name} file upload failed.`);
}
}
}
已上传的文件列表
使用 nzFileList
设置已上传的内容。
import { Component } from '@angular/core';
import { NzUploadFile } from 'ng-zorro-antd/upload';
@Component({
selector: 'nz-demo-upload-default-file-list',
template: `
<nz-upload nzAction="https://www.mocky.io/v2/5cc8019d300000980a055e76" [nzFileList]="fileList">
<button nz-button><i nz-icon nzType="upload"></i>Upload</button>
</nz-upload>
`
})
export class NzDemoUploadDefaultFileListComponent {
fileList: NzUploadFile[] = [
{
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'
}
];
}
完全控制的上传列表
使用 nzFileList
对列表进行完全控制,可以实现各种自定义功能,以下演示二种情况:
上传列表数量的限制。
读取远程路径并显示链接。
import { Component } from '@angular/core';
import { NzUploadChangeParam, NzUploadFile } from 'ng-zorro-antd/upload';
@Component({
selector: 'nz-demo-upload-file-list',
template: `
<nz-upload nzAction="https://www.mocky.io/v2/5cc8019d300000980a055e76" [nzFileList]="fileList" (nzChange)="handleChange($event)">
<button nz-button><i nz-icon nzType="upload"></i>Upload</button>
</nz-upload>
`
})
export class NzDemoUploadFileListComponent {
fileList: NzUploadFile[] = [
{
uid: '-1',
name: 'xxx.png',
status: 'done',
url: 'http://www.baidu.com/xxx.png'
}
];
handleChange(info: NzUploadChangeParam): void {
let fileList = [...info.fileList];
// 1. Limit the number of uploaded files
// Only to show two recent uploaded files, and old ones will be replaced by the new
fileList = fileList.slice(-2);
// 2. Read from response and show file link
fileList = fileList.map(file => {
if (file.response) {
// Component will show file.url as link
file.url = file.response.url;
}
return file;
});
this.fileList = fileList;
}
}
文件夹上传
支持上传一个文件夹里的所有文件。
import { Component } from '@angular/core';
@Component({
selector: 'nz-demo-upload-directory',
template: `
<nz-upload nzAction="https://www.mocky.io/v2/5cc8019d300000980a055e76" nzDirectory>
<button nz-button><i nz-icon nzType="upload"></i> Upload Directory</button>
</nz-upload>
`
})
export class NzDemoUploadDirectoryComponent {}
图片列表样式
上传文件为图片,可展示本地缩略图。IE8/9
不支持浏览器本地缩略图展示(Ref),可以写 thumbUrl
属性来代替。
上传前转换文件
使用 nzTransformFile
转换上传的文件(例如添加水印)。
import { Component } from '@angular/core';
import { NzUploadFile } from 'ng-zorro-antd/upload';
import { Observable, Observer } from 'rxjs';
@Component({
selector: 'nz-demo-upload-transform-file',
template: `
<nz-upload nzAction="https://www.mocky.io/v2/5cc8019d300000980a055e76" [nzTransformFile]="transformFile">
<button nz-button><i nz-icon nzType="upload"></i> Upload</button>
</nz-upload>
`
})
export class NzDemoUploadTransformFileComponent {
transformFile = (file: NzUploadFile) => {
return new Observable((observer: Observer<Blob>) => {
const reader = new FileReader();
// tslint:disable-next-line:no-any
reader.readAsDataURL(file as any);
reader.onload = () => {
const canvas = document.createElement('canvas');
const img = document.createElement('img');
img.src = reader.result as string;
img.onload = () => {
const ctx = canvas.getContext('2d')!;
ctx.drawImage(img, 0, 0);
ctx.fillStyle = 'red';
ctx.textBaseline = 'middle';
ctx.fillText('Ant Design', 20, 20);
canvas.toBlob(blob => {
observer.next(blob!);
observer.complete();
};
};
});
};
}
用户头像
点击上传用户头像,并使用 nzBeforeUpload
限制用户上传的图片格式和大小。
import { Component } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzUploadFile } from 'ng-zorro-antd/upload';
import { Observable, Observer } from 'rxjs';
@Component({
selector: 'nz-demo-upload-avatar',
template: `
<nz-upload
class="avatar-uploader"
nzAction="https://www.mocky.io/v2/5cc8019d300000980a055e76"
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" style="width: 100%" />
</nz-upload>
`,
styles: [
`
:host ::ng-deep .avatar-uploader > .ant-upload {
width: 128px;
height: 128px;
}
]
})
export class NzDemoUploadAvatarComponent {
loading = false;
avatarUrl?: string;
constructor(private msg: NzMessageService) {}
beforeUpload = (file: NzUploadFile, _fileList: NzUploadFile[]) => {
return new Observable((observer: Observer<boolean>) => {
const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
if (!isJpgOrPng) {
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;
}
observer.next(isJpgOrPng && isLt2M);
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);
}
handleChange(info: { file: NzUploadFile }): 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 { NzUploadFile } from 'ng-zorro-antd/upload';
function 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);
});
}
@Component({
selector: 'nz-demo-upload-picture-card',
template: `
<div class="clearfix">
<nz-upload
nzAction="https://www.mocky.io/v2/5cc8019d300000980a055e76"
nzListType="picture-card"
[(nzFileList)]="fileList"
[nzShowButton]="fileList.length < 8"
[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 {
fileList: NzUploadFile[] = [
{
uid: '-1',
name: 'image.png',
status: 'done',
url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png'
},
{
uid: '-2',
name: 'image.png',
status: 'done',
url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png'
},
{
uid: '-3',
name: 'image.png',
status: 'done',
url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png'
},
{
uid: '-4',
name: 'image.png',
status: 'done',
},
{
uid: '-5',
name: 'image.png',
status: 'error'
}
];
previewImage: string | undefined = '';
previewVisible = false;
handlePreview = async (file: NzUploadFile) => {
if (!file.url && !file.preview) {
file.preview = await getBase64(file.originFileObj!);
}
this.previewImage = file.url || file.preview;
this.previewVisible = true;
};
}
拖拽上传
把文件拖入指定区域,完成上传,同样支持点击上传。
import { Component } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzUploadChangeParam } from 'ng-zorro-antd/upload';
@Component({
selector: 'nz-demo-upload-drag',
template: `
<nz-upload
nzType="drag"
[nzMultiple]="true"
nzAction="https://www.mocky.io/v2/5cc8019d300000980a055e76"
(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) {}
handleChange({ file, fileList }: NzUploadChangeParam): 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 } from '@angular/common/http';
import { Component } from '@angular/core';
import { NzUploadFile } from 'ng-zorro-antd/upload';
import { map } from 'rxjs/operators';
@Component({
template: `
<div class="clearfix">
<nz-upload nzAction="https://www.mocky.io/v2/5cc8019d300000980a055e76" nzListType="picture" [nzPreviewFile]="previewFile">
<button nz-button><i nz-icon nzType="upload"></i> Upload</button>
</nz-upload>
</div>
`
})
export class NzDemoUploadPreviewFileComponent {
constructor(private http: HttpClient) {}
previewFile = (file: NzUploadFile) => {
console.log('Your upload file:', file);
return this.http
.post<{ thumbnail: string }>(`https://next.json-generator.com/api/json/get/4ytyBoLK8`, {
method: 'POST',
body: file
})
.pipe(map(res => res.thumbnail));
};
}
阿里云 OSS
使用阿里云 OSS 上传示例.
import { Component } from '@angular/core';
import { NzUploadChangeParam, NzUploadFile } from 'ng-zorro-antd/upload';
@Component({
selector: 'nz-demo-upload-upload-with-aliyun-oss',
template: `
<nz-upload
nzName="file"
[(nzFileList)]="files"
[nzTransformFile]="transformFile"
[nzData]="getExtraData"
[nzAction]="mockOSSData.host"
(nzChange)="onChange($event)"
>
Photos: <button nz-button><i nz-icon nzType="upload"></i> Click to Upload</button>
</nz-upload>
`
})
export class NzDemoUploadUploadWithAliyunOssComponent {
files: NzUploadFile[] = [];
mockOSSData = {
dir: 'user-dir/',
expire: '1577811661',
host: '//www.mocky.io/v2/5cc8019d300000980a055e76',
accessId: 'c2hhb2RhaG9uZw==',
policy: 'eGl4aWhhaGFrdWt1ZGFkYQ==',
signature: 'ZGFob25nc2hhbw=='
};
transformFile = (file: NzUploadFile) => {
const suffix = file.name.slice(file.name.lastIndexOf('.'));
const filename = Date.now() + suffix;
file.url = this.mockOSSData.dir + filename;
return file;
};
getExtraData = (file: NzUploadFile) => {
const { accessId, policy, signature } = this.mockOSSData;
return {
key: file.url,
OSSAccessKeyId: accessId,
policy: policy,
Signature: signature
};
};
onChange(e: NzUploadChangeParam): void {
console.log('Aliyun OSS:', e.fileList);
}
}
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
nzCustomRequest
回调传递以下参数:
onProgress: (event: { percent: number }): void
onError: (event: Error): void
onSuccess: (body: Object, xhr?: Object): void
data: Object
filename: String
file: File
withCredentials: Boolean
headers: Object