Download file to stream instead of File

随声附和 提交于 2019-12-13 20:11:11

问题


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

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.

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

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


回答1:


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.

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



来源:https://stackoverflow.com/questions/37255963/download-file-to-stream-instead-of-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!