3

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

4

1 回答 1

6

这是代码游乐场的一个片段:

  • 在开始之前,请确保您的 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);
    });
  }
于 2019-05-31T09:59:54.013 回答