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

标签 java rest spring-mvc

我一直在尝试使用 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/

相关文章:

json - 使用 Spring MVC、Jackson 和 Hibernate 序列化具有多对多关系的对象

multithreading - resttemplate.exchange()如何在不同的线程上执行?

java - DAO 返回 NullPointerException

java - CopyOnWriteArraySet 中不允许重复,即使它使用内部 CopyOnWriteArrayList 进行所有操作

java - hibernate 错误

java - Maven 基本问题

java - 预 Controller 过滤器的 ExceptionHandler (Spring Security)

java - 有轻量级的独立 SOAP 服务器吗?或者你将如何实现?

ruby-on-rails - Rails 3.1 是否像支持条件 GET 一样支持条件 PUT?

java - Jackson 不使用 setter