我想使用RestTemplate发送文件(服务器仅接受multipart / form-data)。但是,在客户端,我只有JSON对象的字节数组。我不想将其转换为创建文件的文件,因为它需要磁盘空间。我可以将此数据发送到服务器吗?
答案 0 :(得分:0)
您可以尝试
public void uploadDocument(byte[] fileContents, final String filename) {
RestTemplate restTemplate = new RestTemplate();
String fooResourceUrl = "http://localhost:8080/spring-rest/foos"; // Dummy URL.
MultiValueMap<String, Object> map = new LinkedMultiValueMap<String, Object>();
map.add("name", filename);
map.add("filename", filename);
// Here we
ByteArrayResource contentsAsResource = new ByteArrayResource(fileContents) {
@Override
public String getFilename() {
return filename; // Filename has to be returned in order to be able to post.
}
};
map.add("file", contentsAsResource);
// Now you can send your file along.
String result = restTemplate.postForObject(fooResourceUrl, map, String.class);
// Proceed as normal with your results.
}
答案 1 :(得分:0)
这可能应该做您想要的:
首先,创建restTemplate的实例,我通常让spring boot使用@Autowired
自动注入一个:
@Autowired
RestTemplate restTemplate;
现在,有了您的字节数组(在示例中,我将其称为jsonAsByteArray),并假设fileName
作为文件名,将目标服务器的URL分配给String-我将调用url
作为以下示例-;此时,您可以像这样进行操作:
String requestJson = new String(jsonAsByteArray);
MultiValueMap<String, Object> multipartRequest = new LinkedMultiValueMap<>();
HttpHeaders jsonHeaders = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> entity = new HttpEntity<String>(requestJson,jsonHeaders);
multipartRequest.add("file", entity);
multipartRequest.add("fileName", fileName);
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.setContentType(MediaType.MULTIPART_FORM_DATA);
requestHeaders.setAccept(Arrays.asList((new MediaType[] {MediaType.MULTIPART_FORM_DATA})));
HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(multipartRequest, requestHeaders);
ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, multipartRequest, String.class);
检查响应中的结果;您可以像这样在控制台上简单地打印它:
System.out.println(out.getBody());
System.out.println(out.getStatusCode());
编辑:我已根据您的最新评论修改了原始答案。基本上,您必须将包含json的http实体封装到另一个包含多部分请求的更大的http实体中。 全部取自POSTing multipart requests with RestTemplate