一、錯誤的方式
例如,我們在子服務A的controller中,有一個接收Multipartfile文件的POST請求接口,通常寫成如下方式
@PostMapping("/upload")
public String upload(
@RequestParam("pic") MultipartFile pic,
@RequestParam("otherparam") String otherParam
) throws Exception{
//.....
return "success";
}
現在子服務B需要調用A服務上面的接口,在feign中發送file時,很多人習慣寫成下面樣子
@PostMapping("/service_a/upload")
String upload(
@RequestParam("pic") MultipartFile pic,
@RequestParam("otherparam") String otherParam
) throws Exception;
發送請求後,在服務A的控制檯,可以看到報錯日誌如下
org.springframework.web.multipart.MultipartException:Current request is not a multipart request.......
二、正確方式
由上可知,報錯提示當前請求不是一個 multipart request
原因是在feign中,發送 multipartfile文件,應該使用【@RequestPart】而不是【@RequestParam】,且需要設置請求content-type爲【multipart/form-data】,所以正確寫法如下
//正確方式
@PostMapping(value = "/service_a/upload",consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
String upload2(
@RequestPart("pic") MultipartFile pic,
@RequestParam("otherparam") String otherParam
) throws Exception;