这是我的解决方案。我正在使用 Spring Boot 2.4.3
创建 amazon s3 客户端
AmazonS3 amazonS3Client = AmazonS3ClientBuilder
.standard()
.withRegion("your-region")
.withCredentials(
new AWSStaticCredentialsProvider(
new BasicAWSCredentials("your-access-key", "your-secret-access-key")))
.build();
创建一个亚马逊转账客户端。
TransferManager transferManagerClient = TransferManagerBuilder.standard()
.withS3Client(amazonS3Client)
.build();
在/tmp/{your-s3-key}中创建一个临时文件,这样我们就可以将我们下载的文件放在这个文件中。
File file = new File(System.getProperty("java.io.tmpdir"), "your-s3-key");
try {
file.createNewFile(); // Create temporary file
} catch (IOException e) {
e.printStackTrace();
}
file.mkdirs(); // Create the directory of the temporary file
然后,我们使用 transfer manager client
从 s3 下载文件
// Note that in this line the s3 file downloaded has been transferred in to the temporary file that we created
Download download = transferManagerClient.download(
new GetObjectRequest("your-s3-bucket-name", "your-s3-key"), file);
// This line blocks the thread until the download is finished
download.waitForCompletion();
现在 s3 文件已成功传输到我们创建的 临时文件 中。我们可以得到临时文件的InputStream。
InputStream input = new DataInputStream(new FileInputStream(file));
因为临时文件已经不需要了,我们直接删除了。
file.delete();