Angular多文件上传的正确方式?400 Bad Request错误排查
文件上传接口:Insomnia成功但Angular报400错误
我尝试将文件上传至某接口时,用Insomnia能顺利完成,但用Angular实现相同操作却收到400 Bad Request错误。
Insomnia配置情况
- HTTP客户端选项
- 请求头
- 请求负载
我的Angular代码
@Injectable({ providedIn: 'root', }) export class ResourcesService { private readonly ENDPOINT = '/backend/api/content'; constructor(private readonly httpClient: HttpClient) {} upload(files: FileList) { const formData = new FormData(); formData.append('files', files[0], files[0].name); // Array.from(files).forEach((file) => // formData.append('files', file, file.name) // ); // for (let i = 0; i < files.length; i++) { // formData.append('files', files[i], files[i].name); // } return this.httpClient.post<ResourceModel[]>( `${this.ENDPOINT}/upload`, formData, { headers: new HttpHeaders({ 'Content-Type': 'multipart/form-data', }), } ); } }
问题原因及解决方法
问题出在手动设置了Content-Type: multipart/form-data。当发送FormData类型的请求体时,浏览器会自动生成包含boundary分隔符的Content-Type头(比如multipart/form-data; boundary=----WebKitFormBoundaryxxxx),而手动设置的头缺少这个boundary,导致后端无法正确解析请求体,从而返回400错误。
解决方法很简单:删除手动添加的Content-Type配置,让Angular的HttpClient自动处理请求头:
@Injectable({ providedIn: 'root', }) export class ResourcesService { private readonly ENDPOINT = '/backend/api/content'; constructor(private readonly httpClient: HttpClient) {} upload(files: FileList) { const formData = new FormData(); formData.append('files', files[0], files[0].name); // 如果需要批量上传,取消下面的注释即可 // Array.from(files).forEach((file) => // formData.append('files', file, file.name) // ); return this.httpClient.post<ResourceModel[]>( `${this.ENDPOINT}/upload`, formData // 移除手动设置的headers,让HttpClient自动处理 ); } }
如果你的请求需要其他自定义请求头,只需要保留那些头,不要包含Content-Type即可:
return this.httpClient.post<ResourceModel[]>( `${this.ENDPOINT}/upload`, formData, { headers: new HttpHeaders({ 'Authorization': 'Bearer your-token', // 不要加Content-Type }), } );
内容的提问来源于stack exchange,提问作者Mario
相关产品推荐
相关产品推荐

