当我尝试使用我的Spring模板基础测试方法调用以下MultipartFile Spring REST URL时,我遇到了以下异常。我怎样才能做到这一点。谢谢。
Spring REST网址:
@RequestMapping(value = "/media/uploadMultipartFile/{token}/{title}/{trailId}/{wpId}", method = RequestMethod.POST)
public @ResponseBody MediaHttp uploadMultipartFile(@RequestParam MultipartFile file,
@PathVariable String token,
@PathVariable String title,
@PathVariable String trailId,
@PathVariable String wpId,
HttpServletResponse response)
测试方法:
try {
// Message Converters
List<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>();
messageConverters.add(new FormHttpMessageConverter());
messageConverters.add(new SourceHttpMessageConverter<Source>());
messageConverters.add(new StringHttpMessageConverter());
messageConverters.add(new MappingJacksonHttpMessageConverter());
// RestTemplate
RestTemplate template = new RestTemplate();
template.setMessageConverters(messageConverters);
// URL Parameters
MultiValueMap<String, Object> parts = new LinkedMultiValueMap<String, Object>();
parts.add("token", "nkc2jvbrbc");
parts.add("title", "test mp4 file");
parts.add("trailId", "2");
parts.add("wpId", "7");
parts.add("file", new FileSystemResource("C:\\Users\\Public\\Pictures\\Sample Pictures\\test.mp4"));
// Post
MediaHttp result = template.postForObject(Constants.APPLICATION_URL + "/media/uploadMultipartFile/{token}/{title}/{trailId}/{wpId}", parts, MediaHttp.class);
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
例外:
[http://test.com:8080/DMW-skeleton-1.0/media/uploadMultipartFile/ {token} / {title} / {trailId} / {wpId}]中的变量值无效:预期为4;得到0
答案 0 :(得分:11)
消息非常清楚,您没有为提交指定任何路径参数。您只提供将作为请求正文发送的地图。
更改您的调用以包含这些参数作为方法调用的最后一部分。
// URL Parameters
MultiValueMap<String, Object> parts = new LinkedMultiValueMap<String, Object>();
parts.add("file", new FileSystemResource("C:\\Users\\Public\\Pictures\\Sample Pictures\\test.mp4"));
// Post
MediaHttp result = template.postForObject(Constants.APPLICATION_URL + "/media/uploadMultipartFile/{token}/{title}/{trailId}/{wpId}", parts, MediaHttp.class, "nkc2jvbrbc", "test mp4 file", "2", "7);