gpt4 book ai didi

java - 如何将多部分图像文件作为参数传递给 POST REST 服务

转载 作者:太空宇宙 更新时间:2023-11-04 10:59:37 24 4
gpt4 key购买 nike

我一直在尝试使用 POST REST 服务方法在 Java Spring MVC Web 应用程序中上传多部分文件。我使用以下 REST 服务方法来上传文件,当我使用 Postman REST 服务选择文件时,效果很好。

 @RequestMapping(value="/upload", method=RequestMethod.POST)
public @ResponseBody String handleFileUpload( @RequestParam("file") MultipartFile file, ModelMap model)
{
//codes


}

但是当我尝试将多部分文件作为参数传递给 Controller ​​中的 POST REST 服务方法时。它工作得不好。那么我如何将多部分文件作为查询参数传递给 POST REST 服务方法。

  In my controller class I have:



@RequestMapping(value = "/upload-image", method = RequestMethod.POST)
public String uploadProfileImage(@RequestParam("fileUpload") MultipartFile fileUpload, Model model, HttpServletRequest request, HttpServletResponse response)
{
// codes
}

我的 root-context.xml 文件中有以下 bean

<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">


</bean>

感谢任何帮助。

最佳答案

这很简单,但有点奇怪。请使用@PathVariable 而不是@RequestParam。几个月前我就遇到过这种情况。我不知道为什么会这样,但下面的代码片段在我的项目中有效。

    @ResponseBody
@RequestMapping(method = RequestMethod.POST, value = "/upload-image", consumes = MULTIPART_FORM_DATA_VALUE, produces = APPLICATION_JSON_VALUE)
public String uploadProfileImage(@PathVariable("fileUpload") MultipartFile file) {
// ...
}

看看JerseyRestClientMultipartUpload.java获取如何使用 Jersey 发送 MultiPart 的示例。

final MultiPart multiPart = new FormDataMultiPart()
.field("description", "Picture of Jabba the Hutt", MediaType.TEXT_PLAIN_TYPE)
.field("characterProfile", jsonToSend, MediaType.APPLICATION_JSON_TYPE)
.field("filename", fileToUpload.getName(), MediaType.TEXT_PLAIN_TYPE)
.bodyPart(fileDataBodyPart);
multiPart.setMediaType(MediaType.MULTIPART_FORM_DATA_TYPE);

// POST request final
final WebResource resource = client.resource(API_URI)
ClientResponse response = resource.type("multipart/form-data").post(ClientResponse.class, multiPart);

关于java - 如何将多部分图像文件作为参数传递给 POST REST 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47034878/

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