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

using nz-upload i.e (Using ant-design NG-Zorro) custom Request how to upload image

我正在为 angular 6 应用程序使用 NG_ZORRO ant design。我创建了一个组件来使用 nz-upload 上传图像。现在我想使用自定义请求上传包含操作的图片并请求 headers 上传图片。

这是代码游乐场的片段:

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

模板:

<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);
    });
  }

基于阿里云OSS的例子which can be found here

你可以定义

 UploadData = {

    host: 'YOUR_URL',
    custom_field_1:"value"

  };

然后,您可以检索字段

  getExtraData = (file: NzUploadFile): {} => {
    const { custom_field_1} = this.UploadData;

    return {
      custom_field_1
    };
  };

确保更改指令

[nzAction]="UploadData.host"