文件服务器(使用Mongodb作为文件存储数据库),在该应用中,我是通过MultipartFile数组接收多个文件,然后存储到Mongodb数据库中:代码如下:
@PostMapping(value = "/uploads")
public String upload(String detail, String groupId, @RequestParam("files") MultipartFile[] files) throws Exception{
if (SeageUtils.isEmpty(groupId)){
groupId = SeageUtils.getUUID();
}
fileGroupService.upload(detail, groupId, files);
return groupId;
}
那么在其他应用中,使用RestTemplate将前端(安卓或者iOS等客户端)传递过来的参数传到文件服务器,代码如下:
@PostMapping("/clientFilesUploads")
public String clientFilesUploads(String detail,@RequestParam("files") MultipartFile[] files) throws Exception{
MultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
List<Object> fileList = new ArrayList<>();
for(MultipartFile file : files) {
ByteArrayResource byteArrayResource = new ByteArrayResource(file.getBytes());
fileList.add(byteArrayResource);
}
//使用files上传文件
map.put("files", fileList);
map.add("detail",detail);
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(MediaType.MULTIPART_FORM_DATA);
HttpEntity<MultiValueMap<String, Object>> request = new HttpEntity<>(map, httpHeaders);
String url = "http://localhost:8081/group/uploads";
ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, request, String.class);
System.out.println(response.getBody());
return "上传成功!";
}
但是意外的是,在文件服务器接收文件的接口中,并没有获取到任何文件,files的size为0.
这时,我们需要对ByteArrayResource 对象重写getFilename()方法问题才得以解决,将上面代码中的第六行代码:
ByteArrayResource byteArrayResource = new ByteArrayResource(file.getBytes());
修改为:
ByteArrayResource byteArrayResource = new ByteArrayResource(file.getBytes()){
@Override
public String getFilename() throws IllegalStateException {
return file.getOriginalFilename();
}
};