Spring-boot,多部分文件,JVM内存,大文件隧道传输

问题描述 投票:0回答:1

我正在尝试将大型文件从第一个程序发送到第二个,然后从第二个程序发送到第三个。我已使用文件流创建请求]

    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 ...
}

At some point the complete file got stored in memory

有什么方法可以在所有应用程序中流式传输文件

spring-boot memory multipart tunneling large-file-upload
1个回答
0
投票

下面的代码对我有用

    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);

}
© www.soinside.com 2019 - 2024. All rights reserved.