我希望调用一个REST服务,该服务需要以下请求参数。此方法将文件上传到图像服务器。
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public ResponseEntity<String> uploadFile(
@RequestParam("file") MultipartFile file) {
以下是进行服务调用的代码 - 我从图像URL中读取一个BufferedImage对象中的图像。
BufferedImage subImage= ImageIO.read(new URL(<some image url goes here>));
File outputFile = new File("C:\\" + "myimage" + ".jpg");
ImageIO.write(subImage, "jpg", outputFile);
MultiValueMap<String, Object> body = new LinkedMultiValueMap<String, Object>();
String url="http://serviceurl/upload";
body.add("file", outputFile);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
HttpEntity<MultiValueMap<String, Object>> entity = new HttpEntity<MultiValueMap<String, Object>>(body, headers);
restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
正如您所看到的,首先创建了一个文件并保存到磁盘。我该如何避免这一步,仅使用BufferedImage对象(我不想将文件保存到本地磁盘)。
尝试下面的解决方案,但我认为您无法在不将文件保存到磁盘的情况下实现此目的。这是真的吗?
org.springframework.web.multipart.MultipartFile
? - Jobin