将文件下载到流而不是文件 [英] Download file to stream instead of File

查看:107
本文介绍了将文件下载到流而不是文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在实现一个帮助器类,以处理Web应用程序与AWS S3存储之间的传输.

I'm implementing an helper class to handle transfers from and to an AWS S3 storage from my web application.

在我的课程的第一个版本中,我直接使用AmazonS3Client来处理上传和下载,但是现在我发现了TransferManager,我想重构代码以使用它.

In a first version of my class I was using directly a AmazonS3Client to handle upload and download, but now I discovered TransferManager and I'd like to refactor my code to use this.

问题是在我的下载方法中,我以byte[]的形式返回存储的文件.相反,TransferManager仅具有使用File作为下载目标的方法(例如

The problem is that in my download method I return the stored file in form of byte[]. TransferManager instead has only methods that use File as download destination (for example download(GetObjectRequest getObjectRequest, File file)).

我以前的代码是这样的:

My previous code was like this:

GetObjectRequest getObjectRequest = new GetObjectRequest(bucket, key);
S3Object s3Object = amazonS3Client.getObject(getObjectRequest);
S3ObjectInputStream objectInputStream = s3Object.getObjectContent();
byte[] bytes = IOUtils.toByteArray(objectInputStream);

是否可以使用相同的方式使用TransferManager?还是应该继续使用AmazonS3Client实例?

Is there a way to use TransferManager the same way or should I simply continue using an AmazonS3Client instance?

推荐答案

TransferManager使用File对象支持并行下载片段时的文件锁定之类的功能.不能直接使用OutputStream.如果您的要求很简单,例如一次从S3下载小文件,请坚持使用getObject.

The TransferManager uses File objects to support things like file locking when downloading pieces in parallel. It's not possible to use an OutputStream directly. If your requirements are simple, like downloading small files from S3 one at a time, stick with getObject.

否则,您可以使用File.createTempFile创建一个临时文件,并在下载完成后将内容读入字节数组.

Otherwise, you can create a temporary file with File.createTempFile and read the contents into a byte array when the download is done.

这篇关于将文件下载到流而不是文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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