Angular通过FormData上传Excel文件至ASP.NET Core后端失败
上传Excel文件到ASP.NET Core后端时Angular请求返回400错误
我用Angular向ASP.NET Core后端上传Excel文件,Postman中能正常完成上传,但Angular发送请求时收到如下400错误:
{ "type": "https://tools.ietf.org/html/rfc9110#section-15.5.1", "title": "发生了一个或多个验证错误。", "status": 400, "errors": { "file": [ "file字段是必填项。" ] }, "traceId": "00-b1e599ba9962b10481f704228daeddae-372bd43ca76db219-00" }
我的Angular代码
HTTP请求服务代码
uploadFile(file: File): Observable<any> { const formData = new FormData(); formData.append('file', file, file.name); return this.http.post<any>(`${environment.baseApiUri}api/FileLoad/LoadKeepaFile`, formData, { reportProgress: true, observe: 'events', headers: { 'Content-Type': 'multipart/form-data' }, }); }
组件TS代码
onFileSelected(event: any) { this.file = event.target.files[0]; if (this.file) { this.fileName = this.file.name; } } uploadFile() { if (this.file) { this.uploadProgress = 0; this.uploadCancelled = false; this.productManagementService.uploadFile(this.file).subscribe(event => { if (event.type === HttpEventType.UploadProgress) { this.uploadProgress = Math.round(100 * (event.loaded / (event.total ?? 1))); } else if (event.type === HttpEventType.Response) { this.uploadProgress = null; // 处理服务器返回的响应 console.log('文件上传成功', event.body); } }, error => { console.error('上传失败', error); this.uploadProgress = null; }); } } cancelUpload() { this.uploadCancelled = true; this.uploadProgress = null; this.fileName = null; this.file = null; }
说明:Postman可成功上传,Chrome开发者工具中可见请求负载内容。
问题原因及解决方案
问题出在手动设置了Content-Type: multipart/form-data。当发送FormData时,浏览器会自动生成包含boundary参数的Content-Type头(用于分隔表单中的不同字段),手动设置会覆盖这个自动生成的头,且缺失必要的boundary,导致后端ASP.NET Core无法正确解析表单中的file字段,从而返回必填项错误。
修改HTTP请求代码,移除手动设置的headers即可:
uploadFile(file: File): Observable<any> { const formData = new FormData(); formData.append('file', file, file.name); return this.http.post<any>(`${environment.baseApiUri}api/FileLoad/LoadKeepaFile`, formData, { reportProgress: true, observe: 'events' // 移除手动设置的headers配置 }); }
内容的提问来源于stack exchange,提问作者fatihcayir2001
相关产品推荐
相关产品推荐

