问题
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
回答1:
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.
来源:https://stackoverflow.com/questions/16238790/required-string-parameter-is-not-present-with-spring-resttemplate