Spring报错'required part 'file' is not present':前端文件上传失败排查
问题解决:前端发送multipart/form-data后端无法接收file字段
问题出在你手动给请求头设置了带固定boundary的Content-Type。当发送FormData时,浏览器(包括Angular的HttpClient)会自动生成唯一的boundary并添加到Content-Type中,你手动指定的boundary和实际请求里的不一致,导致后端没法正确解析表单里的file部分,所以报错"required part 'file' is not present"。
修改后的前端代码
只保留Authorization头,移除手动设置的Content-Type:
postDogProfilePic(dogId: string, file: File): Observable<any> { let data = new FormData(); data.append("file", file); const httpOptions = { headers: new HttpHeaders({ 'Authorization': 'Bearer ' + this.jwtService.getTokenFromCookies() }) }; return this.http.post(this.url, data, httpOptions); }
原理说明
传递FormData作为请求体时,HttpClient会自动帮你设置正确的multipart/form-data头,包含自动生成的boundary值,和Postman的请求格式一致。手动指定boundary会破坏这个自动机制,让后端无法识别请求中的表单字段。
如果一定要显式设置Content-Type,也不要指定boundary,让浏览器自动处理:
const httpOptions = { headers: new HttpHeaders({ 'Authorization': 'Bearer ' + this.jwtService.getTokenFromCookies(), 'Content-Type': 'multipart/form-data' }) };
修改后再测试,后端就能正常接收MultipartFile了。
内容的提问来源于stack exchange,提问作者TimmYCode
相关产品推荐
相关产品推荐

