如何使用 RestTemplate 转发大文件? [英] How to forward large files with RestTemplate?

查看:57
本文介绍了如何使用 RestTemplate 转发大文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个网络服务调用,通过它可以上传 zip 文件.然后将文件转发到另一个服务进行存储、解压缩等.现在文件存储在文件系统上,然后构建一个 FileSystemResource.

I have a web service call through which zip files can be uploaded. The files are then forwarded to another service for storage, unzipping, etc. For now the file is stored on the file system, then a FileSystemResource is built.

Resource zipFile = new FileSystemResource(tempFile.getAbsolutePath());

我可以使用 ByteStreamResource 来节省时间(在转发之前不需要将文件保存在磁盘上)但为此我需要构建一个字节数组.如果是大文件,我会收到OutOfMemory : java heap space"错误.

I could use a ByteStreamResource in order to save time(the saving of the file on disk is not needed before forwarding) but for that i need to build a byte array. In case of large files I will get an "OutOfMemory : java heap space" error.

ByteArrayResource r = new ByteArrayResource(inputStream.getBytes());

使用 RestTemplate 转发文件而不会出现 OutOfMemory 错误的任何解决方案?

Any solutions to forwarding files without getting an OutOfMemory error using RestTemplate?

推荐答案

编辑:其他答案更好(使用Resource)https://stackoverflow.com/a/36226006/116509

Edit: The other answers are better (use Resource) https://stackoverflow.com/a/36226006/116509

我原来的回答:

您可以使用 execute 进行这种低级操作.在这个片段中,我使用了 Commons IO 的 copy 方法来复制输入流.您需要针对您期望的响应类型自定义 HttpMessageConverterExtractor.

You can use execute for this kind of low-level operation. In this snippet I've used Commons IO's copy method to copy the input stream. You would need to customize the HttpMessageConverterExtractor for the kind of response you're expecting.

final InputStream fis = new FileInputStream(new File("c:\autoexec.bat")); // or whatever
final RequestCallback requestCallback = new RequestCallback() {
     @Override
    public void doWithRequest(final ClientHttpRequest request) throws IOException {
        request.getHeaders().add("Content-type", "application/octet-stream");
        IOUtils.copy(fis, request.getBody());
     }
};
final RestTemplate restTemplate = new RestTemplate();
SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
requestFactory.setBufferRequestBody(false);     
restTemplate.setRequestFactory(requestFactory);     
final HttpMessageConverterExtractor<String> responseExtractor =
    new HttpMessageConverterExtractor<String>(String.class, restTemplate.getMessageConverters());
restTemplate.execute("http://localhost:4000", HttpMethod.POST, requestCallback, responseExtractor);

(感谢 Baz 指出你需要调用 setBufferRequestBody(false) 否则它会失败)

(Thanks to Baz for pointing out you need to call setBufferRequestBody(false) or it will defeat the point)

这篇关于如何使用 RestTemplate 转发大文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆