使用nz-upload即(使用ant-design NG-Zorro)自定义请求上传图片

时间:2018-07-30 07:13:05

标签: angular6 antd ng-zorro-antd

我正在将NG_ZORRO ant设计用于angular 6应用程序。我创建了一个使用nz-upload上传图像的组件。现在,我想使用自定义请求上传包含操作的图像并请求标头以上传图像。

1 个答案:

答案 0 :(得分:0)

这是代码游乐场的摘录:

  • 开始之前,请确保您的HTTP请求拦截器(如果有)未修改标头

模板:

<nz-upload [nzCustomRequest]="customUploadReq" [nzHeaders] = "setMediaUploadHeaders" [nzName]="'file'">
</nz-upload>

TS文件

/* nzUpload: Upload */
import { NzMessageService, UploadFile } from 'ng-zorro-antd';
import { BrowserModule, DomSanitizer } from '@angular/platform-browser'
/* nzUpload: Custom pre-upload checks */
import { /*Observable,*/ Observer } from 'rxjs'; 
/* nzUpload: Custom Upload request */
import { HttpRequest, HttpClient, HttpEventType, HttpEvent, HttpResponse } from '@angular/common/http';
import { UploadXHRArgs } from 'ng-zorro-antd';


  setMediaUploadHeaders = (file: UploadFile) => {
    return {
      "Content-Type": "multipart/form-data",
      "Accept": "application/json",
    }
  };
  customUploadReq = (item: UploadXHRArgs) => {
    const formData = new FormData();
    formData.append('file', item.file as any); // tslint:disable-next-line:no-any
    ///formData.append('id', '1000');
    const req = new HttpRequest('POST', item.action, formData, {
      reportProgress : true,
      withCredentials: false
    });
    // Always return a `Subscription` object, nz-upload will automatically unsubscribe at the appropriate time
   return this.http.request(req).subscribe((event: HttpEvent<{}>) => {
      if (event.type === HttpEventType.UploadProgress) {
        if (event.total > 0) {
          (event as any).percent = event.loaded / event.total * 100; // tslint:disable-next-line:no-any
        }
        // To process the upload progress bar, you must specify the `percent` attribute to indicate progress.
        item.onProgress(event, item.file);
      } else if (event instanceof HttpResponse) { /* success */
        item.onSuccess(event.body, item.file, event);
      }
    },(err) => { /* error */
      item.onError(err, item.file);
    });
  }