📅  最后修改于: 2023-12-03 15:29:32.964000             🧑  作者: Mango
AWS S3 (Amazon Simple Storage Service) 是一项面向互联网应用程序的云存储服务,可在任何可用的 web 浏览器上访问。S3 可以存储大量的数据,并与其他 AWS 服务集成。在 Java 应用程序中,我们可以通过 AWS SDK for Java 访问 S3,实现数据的上传、下载、管理等。
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk-s3</artifactId>
<version>1.12.71</version>
</dependency>
compile 'com.amazonaws:aws-java-sdk-s3:1.12.71'
AWSCredentials credentials = new BasicAWSCredentials("ACCESS_KEY", "SECRET_KEY");
AmazonS3 s3Client = AmazonS3ClientBuilder.standard()
.withCredentials(new AWSStaticCredentialsProvider(credentials))
.withRegion(Regions.US_EAST_1)
.build();
s3Client.putObject("BUCKET_NAME", "OBJECT_KEY", new File("LOCAL_FILE_PATH"));
S3Object s3Object = s3Client.getObject("BUCKET_NAME", "OBJECT_KEY");
S3ObjectInputStream inputStream = s3Object.getObjectContent();
FileUtils.copyInputStreamToFile(inputStream, new File("LOCAL_FILE_PATH"));
s3Client.deleteObject("BUCKET_NAME", "OBJECT_KEY");
ObjectMetadata metadata = s3Client.getObjectMetadata("BUCKET_NAME", "OBJECT_KEY");
System.out.println(metadata.getContentLength());
System.out.println(metadata.getContentType());
默认情况下,S3 的 URL 是虚拟主机样式的,即 URL 中的 Bucket 名称是子域名的一部分。例如:
http://bucket-name.s3.amazonaws.com/object-key
如果需要使用路径样式 URL,即 URL 中的 Bucket 名称直接作为主机名的一部分。例如:
http://s3.amazonaws.com/bucket-name/object-key
可以通过以下方式设置:
s3Client.setS3ClientOptions(new S3ClientOptions().withPathStyleAccess(true));
如果需要通过角色等方式进行身份验证,可以使用临时凭证:
AWSCredentialsProvider credentialsProvider = new STSAssumeRoleSessionCredentialsProvider.Builder("arn", "session-name")
.withRoleSessionDurationSeconds(3600)
.build();
AmazonS3 s3Client = AmazonS3ClientBuilder.standard()
.withCredentials(credentialsProvider)
.withRegion(Regions.US_EAST_1)
.build();
对于大文件上传,可以使用 Amazon S3 支持的分块上传技术。
InitiateMultipartUploadRequest initRequest = new InitiateMultipartUploadRequest(bucketName, keyName);
InitiateMultipartUploadResult initResponse = s3Client.initiateMultipartUpload(initRequest);
File file = new File("LOCAL_FILE_PATH");
long partSize = 5 * 1024 * 1024; //设置分块大小,5MB
long fileLength = file.length();
int partCount = (int) Math.ceil((double) fileLength / partSize); //计算分块数
List<PartETag> partETags = new ArrayList<>();
for (int i = 0; i < partCount; i++) {
long offset = i * partSize;
long currentPartSize = Math.min(partSize, fileLength - offset);
UploadPartRequest uploadRequest = new UploadPartRequest()
.withBucketName(bucketName)
.withKey(keyName)
.withUploadId(initResponse.getUploadId())
.withPartNumber(i + 1)
.withFileOffset(offset)
.withPartSize(currentPartSize)
.withFile(file);
UploadPartResult uploadResult = s3Client.uploadPart(uploadRequest);
partETags.add(uploadResult.getPartETag());
}
CompleteMultipartUploadRequest compRequest = new CompleteMultipartUploadRequest(bucketName, keyName, initResponse.getUploadId(), partETags);
CompleteMultipartUploadResult result = s3Client.completeMultipartUpload(compRequest);