在使用RestTemplate调用文件上传接口的时候,可以使用ByteArrayResource,FileSystemResource,InputStreamResource对文件进行包装
使用ByteArrayResource
如果当前只有字节数组,可以使用这个方式;代码如下:
public void upload(String upLoadUrl, String fileName, byte[] file) {
// 构建header
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
// 把文件封装成ByteArrayResource
ByteArrayResource resource = new ByteArrayResource(file) {
@Override
public String getFilename() {
return fileName;
}
};
// 封装请求体
MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
body.add("file", new HttpEntity<>(resource));
body.add("reportId", "xxx");
// 执行上传
HttpEntity requestEntity = new HttpEntity<>(body, headers);
ResponseEntity<String> response = restTemplate.postForEntity(upLoadUrl, requestEntity, String.class);
log.info(response.getBody());
}
使用FileSystemResource
如果代码中能获取到文件引用,则可以使用该方式;代码如下:
public void upload02(String upLoadUrl, String fileName, File file) {
// 构建header
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
// 把文件封装成 FileSystemResource
FileSystemResource resource = new FileSystemResource(file);
// 封装请求体
MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
body.add("file", new HttpEntity<>(resource));
body.add("reportId", "xxx");
// 执行上传
HttpEntity requestEntity = new HttpEntity<>(body, headers);
ResponseEntity<String> response = restTemplate.postForEntity(upLoadUrl, requestEntity, String.class);
log.info(response.getBody());
}
使用InputStreamResource
示例:
public void upload03(String upLoadUrl, String fileName, InputStream inputStream, long cententLength) {
// 构建header
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
// 把文件封装成 InputStreamResource
InputStreamResource resource = new InputStreamResource(inputStream) {
@Override
public long contentLength() {
return cententLength;
}
@Override
public String getFilename() {
return fileName;
}
};
// 封装请求体
MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
body.add("file", new HttpEntity<>(resource));
body.add("reportId", "xxx");
// 执行上传
HttpEntity requestEntity = new HttpEntity<>(body, headers);
ResponseEntity<String> response = restTemplate.postForEntity(upLoadUrl, requestEntity, String.class);
log.info(response.getBody());
}
over~~