简体   繁体   中英

Required String parameter is not present with Spring RestTemplate

I am having trouble to post 2 parameters with RestTemplate :

  • a String
  • a MultipartFile

I don't think there is a problem in my controller because it's very basic. It seems that the controller doesn't received the name parameter. Could you tell me what's wrong in my code

The controller (the receiver)

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

The Rest client (the sender)

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);

The controller stackTrace

org.springframework.web.bind.MissingServletRequestParameterException: Required String parameter 'name' is not present

Handling multipart requests is a complex process. It's not as simple as reading request parameters. As such, Spring requires you to declare a MultipartResolver so that it can parse and handle such requests. You can do this in your applicationContext.xml file:

<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>

Where CommonsMultipartResolver is the implementation that parse your request and split the parts so that your controller can find the plain request parameters and the file(s) uploaded.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM