无法在Angular FileUpload控件中设置Content-Type

时间:2018-08-31 12:40:22

标签: asp.net-mvc angular primeng

我在Angular项目中有一个PrimeNG FileUpload控件,并且我手动调用了PrimeNG manually invoke FileUpload所示的上载方法。但是,尽管我已经用文件数据正确填充了files参数,但是数据从service.ts传递到Controller(ASP.NET MVC)后丢失了其值并返回null。我认为问题是由于无法在所有事件中都设置Content-Type引起的,如下所示:

onBeforeSendFile(event: any) {
    event.xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
    event.xhr.setRequestHeader("Content-Type", "multipart/form-data");
}

or

onBeforeUploadFile(event: any) {
    event.xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
    event.xhr.setRequestHeader("Content-Type", "multipart/form-data");
}

等...

我在setRequestHeader行中遇到“无法读取未定义的属性'setRequestHeader'”错误。您能告诉我如何设置必要的RequestHeaders而不丢失文件数据吗?

更新: 这是我下面的发布方法:

 post(url: string, body: any, comp?: BaseComponent): Observable<any> {
    this.requestInterceptor(comp);
    return this.http.post<any>(url, { body: JSON.stringify(body) },
        {
            headers: new HttpHeaders({  // set the header values here
                'Content-Type': 'multipart/form-data',
                'X-Requested-With': 'XMLHttpRequest',
                'Test-Header': 'This is just a test header!'
            })
        }
    ).pipe(
        catchError((error, obs) => this.handleError(error, comp)),
        tap((res: Response) => {
            this.onSubscribeSuccess(res, comp);
        }, (error: any) => {
            this.onSubscribeError(error, comp);
        }),
        finalize(() => {
            this.onFinally(comp);
        }));
}

1 个答案:

答案 0 :(得分:1)

您可以改为使用HttpClient,例如:

O(1)