我目前正在嘗試編寫一個接受文件上傳的ReST方法。當用戶提交文件時,我也希望他們添加一個描述以及一些其他與文件內容有關的元數據(例如,與文件內容相關的「類型」)。我使用Spring MVC的控制器使用Spring 4我可以在Spring Rest方法中混合媒體類型嗎?
這是我想要做的一個例子:
@RequestMapping(value = "/file", method = RequestMethod.POST)
public @ResponseBody
ResponseEntity<MyFileDTO> uploadCustomAnnotationFile(
@RequestParam("file") MultipartFile uploadFile,
@RequestBody MyFileDetailsDTO fileDetails) {
log.debug("This is working!");
}
但是,如果我嘗試調用通過揚鞭UI這種方法,我得到一個不支持的媒體類型的異常:
org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'multipart/form-data;boundary=----WebKitFormBoundarycAbgNBTQ09GQTBif' not supported
我懷疑我不能在1個請求混合應用/ JSON和多部分/格式數據?
更新: 基於zeroflagL的響應和跟隨提供的特定於我正在嘗試執行的文檔的鏈接,並使用@RequestPart而不是@RequestBody,我取得了很小的進展,但這仍然不起作用。
新方法簽名:
@RequestMapping(value = "/file", method = RequestMethod.POST)
public @ResponseBody
ResponseEntity<MyFileDTO> uploadCustomAnnotationFile(
@RequestPart MultipartFile uploadFile,
@RequestPart MyFileDetailsDTO fileDetails) {
log.debug("This is working!");
}
新的異常:
2014-12-11 09:21:45.237 [http-nio-8443-exec-8] ERROR c.i.h.c.ControllerExceptionHandler [ControllerExceptionHandler.groovy:58] - Controller Exception
org.springframework.web.multipart.support.MissingServletRequestPartException: Required request part 'fileDetails' is not present.
在此先感謝, 湯妮雅
請注意,如果您的@Controller類在@ RequestMapping的「consumes」屬性中聲明瞭錯誤的端點格式,例如如果您聲明'consumes = {「application/json」},則也會拋出'HttpMediaTypeNotSupportedException '在課堂上,但是有一個終端需要使用「multipart/form-data」。 – lanoxx 2016-07-31 20:07:55