版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/WRian_Ban/article/details/88076869
nzBeforeUpload
返回 false 后,使用手动上传按钮替换上传按钮。
xxx.component.html
<nz-upload
class="import-excel"
[(nzFileList)]="fileList"
[nzBeforeUpload]="beforeUpload"
*ngIf="fileList.length == 0"
>
<button nz-button>Import From Excel</button>
</nz-upload>
<button
nz-button
class="import-excel"
[nzType]="'primary'"
[nzLoading]="uploading"
(click)="handleUpload()"
*ngIf="fileList.length > 0"
>
{{ uploading ? 'Uploading' : 'Start Upload' }}
</button>
xxx.component.ts
import { HttpClient, HttpRequest, HttpResponse } from '@angular/common/http'; // 载入必要模块
import { NzMessageService, UploadFile } from 'ng-zorro-antd';
import { filter } from 'rxjs/operators';
·
·
·
export class XXXComponent implements OnInit, OnChanges {
constructor(
private message: NzMessageService,
private http: HttpClient, // 注册
) { }
···
uploading = false; // 初始值
fileList: UploadFile[] = [];
·
·
·
beforeUpload = (file: UploadFile): boolean => {
this.fileList = this.fileList.concat(file); // 将上传内容存入fileList
if (file.type !== 'image/png') { // 检查格式
this.message.error(`Sorry, The file format is incorrect and only supports PNG format.`);
this.uploading = false;
this.fileList = [];
}
return false; // 手动上传的关键
}
handleUpload(): void { // 手动上传
const formData = new FormData();
this.fileList.forEach((file: any) => {
formData.append('files[]', file);
});
this.uploading = true; // 修改上传按钮状态
const req = new HttpRequest('POST', 'https://jsonplaceholder.typicode.com/posts/', formData, { });
this.http
.request(req)
.pipe(filter(e => e instanceof HttpResponse))
.subscribe(
() => {
this.uploading = false;
this.fileList = [];
this.message.success('upload successfully.');
this.ngOnInit(); // 上传成功后,可根据需要重新渲染页面
},
() => {
this.uploading = false;
this.fileList = [];
this.message.error('upload failed.');
}
);
}