无法在 Angular FileUpload 控件中设置 Content-Type [英] Cannot set Content-Type in Angular FileUpload control
问题描述
我的 Angular 项目中有一个 PrimeNG FileUpload 控件,我手动调用上传方法,如 PrimeNG 所示调用文件上传.但是,尽管我已经用文件数据正确地填充了 files 参数,但在从 service.ts 传递到 Controller (ASP.NET MVC) 后,数据丢失了其值并返回 null.我认为问题是由于无法在任何事件中设置 Content-Type 引起的,如下所示:
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");
}
等等...
我在 setRequestHeader 行遇到无法读取未定义的属性‘setRequestHeader’"错误.你能告诉我如何设置必要的 RequestHeaders 而不会丢失文件数据吗?
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?
更新:下面是我的发帖方法:
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);
}));
}
推荐答案
你可以使用 HttpClient 而是喜欢:
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'
})
});
这篇关于无法在 Angular FileUpload 控件中设置 Content-Type的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!