Spring RestTemplate不提供必需的String参数

The*_*ook 4 java rest spring spring-mvc resttemplate

我无法使用RestTemplate发布2个参数:

  • 一个字符串
  • 多部件文件

我不认为我的控制器有问题,因为它非常基本.似乎控制器没有收到name参数.你能告诉我我的代码有什么问题吗?

控制器(接收器)

@RequestMapping(value="/fileupload", method=RequestMethod.POST)
public void handleFileUpload(@RequestParam("name") String fileUploadHandlerName,
                             @RequestParam("file") MultipartFile file)
{
    [...]
}
Run Code Online (Sandbox Code Playgroud)

Rest客户端(发件人)

RestTemplate rest = new RestTemplate();
URI uri = new URI("http://127.0.0.1:7011/xxxxxxxx/admin/fileupload");

MultiValueMap<String, Object> parts = new LinkedMultiValueMap<String, Object>();
parts.add("name", "import_keys");
Resource file = new ClassPathResource("xmlFileImport/file.xml");
parts.add("file", file);

rest.postForLocation(uri, parts);
Run Code Online (Sandbox Code Playgroud)

控制器stackTrace

org.springframework.web.bind.MissingServletRequestParameterException:必需字符串参数'name'不存在

Sot*_*lis 5

处理多部分请求是一个复杂的过程.它并不像读取请求参数那么简单.因此,Spring要求您声明一个,MultipartResolver以便它可以解析和处理这些请求.您可以在您的applicationContext.xml文件中执行此操作:

<bean id="multipartResolver"  
    class="org.springframework.web.multipart.commons.CommonsMultipartResolver">  
    <property name="maxUploadSize">  
        <value> <YOUR_SIZE> </value>  
    </property>  
    <property name="maxInMemorySize">  
        <value> <YOUR_SIZE> </value>  
    </property>      
</bean>
Run Code Online (Sandbox Code Playgroud)

CommonsMultipartResolver解析您的请求并拆分部件的实现在哪里,以便您的控制器可以找到普通请求参数和上载的文件.