HTML页面
<nz-upload
nzAccept="application/pdf,image/jpeg,image/jpg,image/png"
[(nzFileList)]="fileList"
[(nzAction)]="UPLOAD_FILE"
[nzShowButton]="fileList.length < 1"
[nzBeforeUpload]="beforeUpload"
(nzChange)="getFileUrl($event)" >
<button nz-button>
<i nz-icon nzType="upload"></i>
<span>上传文件</span>
</button>
</nz-upload>
ts文件
import { Component, OnInit } from '@angular/core';
import { NzMessageService, NzModalService, UploadFile } from 'ng-zorro-antd';
@Component({
selector: 'app-detail',
templateUrl: './detail.component.html',
styleUrls: ['./detail.component.scss']
})
export class DetailComponent implements OnInit {
UPLOAD_FILE = ''; // 文件上传路径
constructor(
private activeRoute: ActivatedRoute,
private msg: NzMessageService,
private router: Router,
private message: NzModalService,
){ }
fileList: UploadFile[] = [];
beforeUpload = (file: UploadFile): boolean => {
// 对上传文件类型进行判断
const type = file.type;
const str = ['application/pdf', 'image/jpg', 'image/jpeg', 'image/png'];
if (str.indexOf(type) < 0) {
this.message.warning({
nzTitle: '提示',
nzContent: '选择文件失败,仅支持pdf、jpg、jpeg、png等格式的文件'
});
return false;
}
// 对上传文件大小进行限制
const isLt20M = file.size / 1024 / 1024 < 30;
if (!isLt20M) {
this.message.warning({
nzTitle: '提示',
nzContent: '文件必须在30M以内'
});
return false;
}
this.fileList = this.fileList.concat(file);
// 当类型与大小都符合要求,直接上传;如return false,则需手动调用上传方法
return true;
}
//文件上传完成获取路径的方法
getFileUrl({ file, fileList }): void {
const status = file.status;
if (status === 'done') {
this.zizhi_prove = file.response.data
} else if (status === 'error') {
this.msg.error(`${file.name} file upload failed.`);
}
}
}