以往多用RestTemplate处理接口的调用以及与Ribbon/Feign配合使用调用微服务接口,近日写了一个处理Post文件上传的解决方案,其实就是将后台所需的MultipartFile,在请求ParamMap中,value类型存储为FileSystemResource。代码如下:
String url = "http://*.*.110.9:9100/liveness-detect/detect"; String filePath = "/home/lab/liveness-examples/t1.mp4"; RestTemplate rest = new RestTemplate(); FileSystemResource resource = new FileSystemResource(new File(filePath)); MultiValueMap<String, Object> param = new LinkedMultiValueMap<>(); Float[] f = new Float[0]; param.add("file", resource); param.add("region", f); String string = rest.postForObject(url, param, String.class); System.out.println(string);