Spring Rest Controller
@PostMapping(
value = "/post",
produces = MediaType.APPLICATION_JSON_VALUE,
consumes = {MediaType.APPLICATION_JSON_VALUE, MediaType.MULTIPART_FORM_DATA_VALUE}
)
public ResponseEntity<User> handleFileUpload(@RequestParam("user") User user, @RequestPart("file") MultipartFile file) {
// do something with User and file
return ResponseEntity.ok().build();
}
Angular Service
@Injectable()
export class UploadFileService {
constructor(private http: HttpClient) { }
pushFileToStorage(file: File): Observable<HttpEvent<{}>> {
let formdata: FormData = new FormData();
formdata.append('file', file);
formdata.append('user', JSON.stringify(new User('John', 12)))
const req = new HttpRequest('POST', '/post', formdata, {
reportProgress: true,
});
return this.http.request(req);
}
}
当我尝试发送请求时,会收到500内部服务器错误
。
以下是请求头
POST /post HTTP/1.1
Host: localhost:4200
Connection: keep-alive
Content-Length: 152881
Accept: application/json, text/plain, */*
Content-Type: multipart/form-data; boundary=----WebKitFormBoundarydaQb5yaWw2xu1V9r
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
请求有效负载
------WebKitFormBoundarydaQb5yaWw2xu1V9r
Content-Disposition: form-data; name="file"; filename="Screen Shot 2017-10-24 at 8.49.13 PM.png"
Content-Type: image/png
------WebKitFormBoundarydaQb5yaWw2xu1V9r
Content-Disposition: form-data; name="user"
{"name":"John","age":12}
------WebKitFormBoundarydaQb5yaWw2xu1V9r--
注意:如果在Spring rest controller中,将参数类型User更改为String,则可以正常工作。
问题:如何从Angular发送请求,以便在Spring中获取User和MultipartFile,而不是String。