我正在尝试将大型文件从第一个程序发送到第二个,然后从第二个程序发送到第三个。我已使用文件流创建请求]
public static void main(String[] args) throws IOException {
RestTemplate restTemplate=new RestTemplate();
File file=new File("large-file");
MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
body.add("file",new MultipartInputStreamFileResource(new
FileInputStream(file),"large-file"));
body.add("name", "large-file");
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);
ResponseEntity<Resource> response =
restTemplate.postForEntity("http://localhost:8081/files", requestEntity,
Resource.class);
}
class MultipartInputStreamFileResource extends InputStreamResource {
private final String filename;
MultipartInputStreamFileResource(InputStream inputStream, String filename) {
super(inputStream);
this.filename = filename;
}
@Override
public String getFilename() {
return this.filename;
}
@Override
public long contentLength() throws IOException {
return -1; // we do not want to generally read the whole stream into memory ...
}
有什么方法可以在所有应用程序中流式传输文件
下面的代码对我有用
public static void main(String[] args) throws IOException {
RestTemplate restTemplate=new RestTemplate();
SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
requestFactory.setBufferRequestBody(false);
restTemplate.setRequestFactory(requestFactory);
File file=new File("large-file.txt");
MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
MultipartInputStreamFileResource res= new MultipartInputStreamFileResource(new FileInputStream(file),"large-file.txt");
body.add("file",res);
body.add("name", "large-file.txt");
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
headers.setContentLength(res.contentLength());
HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);
System.out.println();
ResponseEntity<Resource> response = restTemplate.postForEntity("http://localhost:8081/files", requestEntity,
Resource.class);
}