使用ngZorro中Upload自定义上传时XMLHttpRequest问题解决方法

使用ngZorro中Upload自定义上传时XMLHttpRequest问题解决方法


使用angular框架写前端的用户一般都比较喜欢用ngZorro,本人最近在使用ngZorro中的Upload自定义文件组件(链接: ngZorro自定义上传)上传时遇到如下问题。
问题描述:

该组件实例代码

import { HttpClient, HttpEvent, HttpEventType, HttpRequest, HttpResponse } from '@angular/common/http';
import { Component } from '@angular/core';
import { UploadXHRArgs } from 'ng-zorro-antd';
import { forkJoin } from 'rxjs';

@Component({
  selector: 'nz-demo-upload-custom-request',
  template: `
    <nz-upload nzAction="https://jsonplaceholder.typicode.com/posts/" [nzCustomRequest]="customReq">
      <button nz-button><i nz-icon nzType="upload"></i><span>Click to Upload</span></button>
    </nz-upload>
  `
})
export class NzDemoUploadCustomRequestComponent {
  constructor(private http: HttpClient) {}

  customReq = (item: UploadXHRArgs) => {
    // Create a FormData here to store files and other parameters.
    const formData = new FormData();
    // tslint:disable-next-line:no-any
    formData.append('file', item.file as any);
    formData.append('id', '1000');
    const req = new HttpRequest('POST', item.action!, formData, {
      reportProgress: true,
      withCredentials: true
    });
    // Always returns a `Subscription` object. nz-upload would automatically unsubscribe it at correct time.
    return this.http.request(req).subscribe(
      (event: HttpEvent<{}>) => {
        if (event.type === HttpEventType.UploadProgress) {
          if (event.total! > 0) {
            // tslint:disable-next-line:no-any
            (event as any).percent = (event.loaded / event.total!) * 100;
          }
          item.onProgress!(event, item.file!);
        } else if (event instanceof HttpResponse) {
          item.onSuccess!(event.body, item.file!, event);
        }
      },
      err => {
        item.onError!(err, item.file!);
      }
    );
  };

解决方法:
将withCredentials的值由true改为false。

 const req = new HttpRequest('POST', item.action!, formData, {
      reportProgress: true,
      withCredentials: false
    });
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值