我看過很多來源,也很少有關于 SO 的問題,但沒有找到解決方案。
我想將包含 JSON 物件Car和附加檔案的POST/PUT 請求發送到我的 Spring 應用程式。
目前我有一個CarController可以正確使用 JSON 物件的
@PutMapping("/{id}/update")
public void updateCar(@PathVariable(value = "id") Long carId, @Validated @RequestBody Car car) throws ResourceNotFoundException {
// I can work with received car
}
我也有一個FileController可以正確使用的file
@PostMapping("/upload")
public void uploadFiles(@RequestParam("file") MultipartFile file) throws IOException {
// I can work with received file
}
但是我的方法應該如何才能同時使用car和file?此代碼不為我提供任何car或file。
@PutMapping("/{id}/update")
public void updateCar(@PathVariable(value = "id") Long carId, @Validated @RequestBody Car car, @RequestParam("file") MultipartFile file) throws ResourceNotFoundException, IOException {
// can not work neither with car nor with file
}
在 Postman 測驗期間,單獨的控制器運行良好。但是當我嘗試第三個代碼時,我得到了這些結果:


uj5u.com熱心網友回復:
您可以使用注釋consumes = { MediaType.MULTIPART_FORM_DATA_VALUE }欄位@RequestMapping和@RequestPart方法引數注釋:
ResponseEntity<> foo(@RequestPart ParType value, @RequestPart MultipartFile anotherChoice) {
...
uj5u.com熱心網友回復:
是的,我
- 使用正文>表單資料
- 當問題:
- 顯示
Content-Type欄。 Content-Type每部分設定。
- 顯示
uj5u.com熱心網友回復:
您的代碼沒有任何問題,它可以按原樣作業。
當它是多部分請求時,您最終可以通過使用 @RequestPart 而不是 @RequestParam 和 @RequestBody 來提高其可讀性。
您可以在本文
選中“Content-Type”框,新列將出現:

最后,定義每個部分的內容型別。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/366567.html
下一篇:你好,我在做一個學校專案,我試圖在PostgreSQL中使用SpringSecurity,我想從資料庫中獲取用戶,但我不知道出了什么問題
