gpt4 book ai didi

java - 我可以在 Spring Rest 方法中混合媒体类型吗?

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:00:33 24 4
gpt4 key购买 nike

我目前正在尝试编写一个接受文件上传的 ReST 方法。当用户提交文件时,我还希望他们添加描述和一些其他有关文件内容的元数据(例如,与文件内容相关联的“类型”)。我正在使用 Spring MVC Controller 和 Spring 4。

这是我想做的一个例子:

@RequestMapping(value = "/file", method = RequestMethod.POST)
public @ResponseBody
ResponseEntity<MyFileDTO> uploadCustomAnnotationFile(
@RequestParam("file") MultipartFile uploadFile,
@RequestBody MyFileDetailsDTO fileDetails) {
log.debug("This is working!");
}

但是,如果我尝试通过 Swagger UI 调用此方法,我会收到不受支持的媒体类型异常:

org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'multipart/form-data;boundary=----WebKitFormBoundarycAbgNBTQ09GQTBif' not supported

我怀疑我不能在 1 个请求中混合使用 application/json 和 multipart/form-data?

更新:根据 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.

提前致谢,冬妮娅

最佳答案

您可以在 Spring REST 方法中混合媒体类型。 @zeroflagL/回答可能是对的。但是 @RequestPart 工作正常。这是我的代码,和你的没什么不同

@RequestMapping(value = "/interface/member/v1/register.do", method = RequestMethod.POST)
@ResponseBody
public RegisterResponse register(@RequestPart(value = "registerRequest") RegisterRequest registerRequest,
@RequestPart(value = "attachment", required = false) MultipartFile file) throws ServiceException {
return memberV1Service.register(registerRequest, file);
}

我建议,你应该检查你的请求。不是您的服务器端代码。这是我的测试预览代码(我使用 Postman 在 Chrome 中测试)

    POST /was/interface/member/v1/register.do HTTP/1.1
Host: localhost:8080
Cache-Control: no-cache

----WebKitFormBoundaryE19zNvXGzXaLvS5C
Content-Disposition: form-data; name="registerRequest"

{ -- some of my json format content}
----WebKitFormBoundaryE19zNvXGzXaLvS5C
Content-Disposition: form-data; name="attachment"; filename="IMG_0089.JPG"
Content-Type: image/jpeg


----WebKitFormBoundaryE19zNvXGzXaLvS5C

请求中缺少内容类型。此测试因 MissingServletRequestPartException 而失败,因为所需的请求部分“registerRequest”不存在。

您可以使用 RESTClient 或其他工具进行测试,并检查 Content-Type 是否存在。

关于java - 我可以在 Spring Rest 方法中混合媒体类型吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27413505/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com