客户端:
public class SendFile {
public static void main(String[] args) {
RestTemplate restTemplate = new RestTemplate();
SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
requestFactory.setBufferRequestBody(false);
restTemplate.setRequestFactory(requestFactory);
File file = new File("D:\\software\\test.txt");
File file2 = new File("D:\\software\\test2.txt");
MultiValueMap<String,Object> parts = new LinkedMultiValueMap<>();
try {
parts.add("files", new MultipartFileResource(new FileInputStream(file),"test"));
parts.add("files", new MultipartFileResource(new FileInputStream(file2),"text2"));
} catch (IOException e) {
throw new RuntimeException(e);
}
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
HttpEntity<MultiValueMap<String,Object>> request = new HttpEntity<>(parts, headers);
ResponseEntity<String> ret =restTemplate.exchange("http://localhost:8886/file/reciveFile", HttpMethod.POST, request, String.class);
System.out.println(ret.getBody().toString());
}
public class MultipartFileResource extends InputStreamResource {
//命名没错哦 就是这个名字
private String filename;
public MultipartFileResource(InputStream inputStream, String filename) {
super(inputStream);
this.filename = filename;
}
//这个必须写
@Override
public String getFilename() {
return this.filename;
}
//这个必须写
@Override
public long contentLength() throws IOException {
// we do not want to generally read the whole stream into memory ...
return -1;
}
}
服务器:
@RequestMapping(value="/file/reciveFile",method=RequestMethod.POST)
public Result reciveFile(List<MultipartFile> files) throws IOException {
//获取文件名
files.get(0).getName();
//获取输入流
files.get(0).getInputStream();
//获取长度
files.get(0).getInputStream().available();
return null;
}
备注:
fileResource那个类,必须重写getFilename和contentLength,变量名就是filename