我无法使用 RestTemplate 发布 2 个参数:
I am having trouble to post 2 parameters with RestTemplate :
- 一个字符串
- 一个多部分文件
我认为我的控制器没有问题,因为它非常基础.控制器似乎没有收到 name 参数.你能告诉我我的代码有什么问题吗
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
控制器(接收器)
@RequestMapping(value="/fileupload", method=RequestMethod.POST) public void handleFileUpload(@RequestParam("name") String fileUploadHandlerName, @RequestParam("file") MultipartFile file) { [...] }Rest 客户端(发送方)
RestTemplate rest = new RestTemplate(); URI uri = new URI("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);控制器堆栈跟踪
org.springframework.web.bind.MissingServletRequestParameterException:所需的字符串参数名称"不存在
org.springframework.web.bind.MissingServletRequestParameterException: Required String parameter 'name' is not present
推荐答案处理多部分请求是一个复杂的过程.它不像读取请求参数那么简单.因此,Spring 要求您声明一个 MultipartResolver 以便它可以解析和处理此类请求.您可以在 applicationContext.xml 文件中执行此操作:
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.multipartmons.CommonsMultipartResolver"> <property name="maxUploadSize"> <value> <YOUR_SIZE> </value> </property> <property name="maxInMemorySize"> <value> <YOUR_SIZE> </value> </property> </bean>哪里 CommonsMultipartResolver 是解析您的请求并拆分部分的实现,以便您的控制器可以找到普通的请求参数和上传的文件.
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.
更多推荐
Spring RestTemplate 不存在必需的字符串参数
发布评论