Cannot set Content-Type in Angular FileUpload control

大憨熊 提交于 2019-12-25 00:09:44

问题


I have an PrimeNG FileUpload control in my Angular project and I manually invoke upload method as shown on PrimeNG manually invoke FileUpload. However, although I have properly fill the files parameter with file data, the data lost its value and returns null after passing from service.ts to Controller (ASP.NET MVC). I think the problem is caused by not being able to set Content-Type in none of the events as shown below:

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

etc...

I encounter "Cannot read property 'setRequestHeader' of undefined" error ath the setRequestHeader lines. Could you please inform me how can I set the necessary RequestHeaders and not lost the file data?

Update: Here is my post method below:

 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:


You can use HttpClient instead like:

this._HttpClient.post('url whatever', { 'body': 'here' }, {
    headers: new HttpHeaders({  // set the header values here
        'Content-Type': 'multipart/form-data'
    })
});


来源:https://stackoverflow.com/questions/52115680/cannot-set-content-type-in-angular-fileupload-control

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!