使用Spring 4 restTemplate(Java Client和RestController)上传MultipartFile列表
我试图使用spring restTemplate将List of MultipartFile发布到我的RestController,尽管我对我的客户端和控制器使用的确切语法和类型有点困惑。 基于我所做的研究,到目前为止我所拥有的……
FileUploadClient.java
public void uploadFiles(List multiPartFileList) throws IOException { MultiValueMap map = new LinkedMultiValueMap(); List files = new ArrayList(); for(MultipartFile file : multiPartFileList) { files.add(new ByteArrayResource(file.getBytes())); } map.put("files", files); // headers is inherited from BaseClient headers.setContentType(MediaType.MULTIPART_FORM_DATA); HttpEntity<MultiValueMap> request = new HttpEntity(map, headers); ResponseEntity response = restTemplate.exchange(restURI + "/rest/fileupload/uploadfiles", HttpMethod.POST, request, String.class); if(HttpStatus.OK.equals(response.getStatusCode())) { System.out.println("status for /rest/fileupload/uploadfiles ---> " + response); } }
FileUploadRestController.java
@RequestMapping(value = "/uploadfiles", method = RequestMethod.POST) public ResponseEntity uploadFiles(@RequestParam("files") List files, HttpServletRequest request) { ResponseEntity response; try { // do stuff... response = new ResponseEntity(header, HttpStatus.OK); System.out.println("file uploaded"); } catch (Exception e) { // handle exception } return response; }
web.xml中
multipartFilter org.springframework.web.multipart.support.MultipartFilter multipartFilter /*
为spring-servlet.xml
如果我理解正确的话。 多部分filter应该将我的MultiValueMap解析为MultipartFiles列表和MultipartHttpServletRequest? 我可以让我的客户端访问我的RestController的唯一方法是将文件数据作为ByteArrayResource发送,但是在我的Controller中,我的RequestBody始终为null,而MultipartHttpServletRequest的multipartFiles属性则为空映射。 我看了很多post试图解决这个问题,但无济于事。 任何帮助将非常感激。
看起来您从FileUploadClient
发送的request
有效负载与服务器期望的不匹配。 您可以尝试更改以下内容:
MultiValueMap map = new LinkedMultiValueMap<>(); for(MultipartFile file : multiPartFileList) { map.add(file.getName(), new ByteArrayResource(file.getBytes())); }
至
MultiValueMap map = new LinkedMultiValueMap<>(); List files = new ArrayList<>(); for(MultipartFile file : multiPartFileList) { files.add(new ByteArrayResource(file.getBytes())); } map.put("files", files);
此外,您是否可以尝试将服务器的方法签名更改为以下内容:
public ResponseEntity> uploadFiles(@RequestParam("files") List files, HttpServletRequest request) {
更新
在上传多个文件时,您需要确保ByteArrayResource
getFileName
每次都返回相同的值。 如果没有,您将始终获得一个空数组。
例如以下为我工作:
客户:
MultiValueMap data = new LinkedMultiValueMap(); for(MultipartFile file : multiPartFileList) { ByteArrayResource resource = new ByteArrayResource(file.getBytes()) { @Override public String getFilename() { return ""; } }; data.add("files", resource); }
服务器
public ResponseEntity> upload(@RequestParam("files") MultipartFile[] files){