我在使用 RestTemplate 发布 2 个参数时遇到问题:
- 一个字符串
- 一个多部分文件
我认为我的 Controller 没有问题,因为它非常基础。似乎 Controller 没有收到 name 参数。你能告诉我我的代码有什么问题吗
Controller (接收器)
@RequestMapping(value="/fileupload", method=RequestMethod.POST)
public void handleFileUpload(@RequestParam("name") String fileUploadHandlerName,
@RequestParam("file") MultipartFile file)
{
[...]
}
The Rest client(发件人)
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);
Controller 堆栈跟踪
org.springframework.web.bind.MissingServletRequestParameterException: Required String parameter 'name' is not present
最佳答案
处理多部分请求是一个复杂的过程。不是读取请求参数那么简单。因此,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>
在哪里CommonsMultipartResolver
是解析您的请求并拆分各个部分的实现,以便您的 Controller 可以找到普通请求参数和上传的文件。
关于java - Spring RestTemplate 不存在必需的字符串参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16238790/