Angular实战记录---ant Design手动上传

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.');
		        }
		      );
		  }
		  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值