AWS DynamoDB及S3操作文档(一)
AWS S3的简单操作(连接、桶的创建、对象上传、下载)
1.1 AWS S3的连接
- 在控制台创建桶并获取Access_key_ID和Secret_access_key
获取Access_key_ID和Secret_access_key的方式可参考§1.1(3)。
创建桶过程如下:
①登录 AWS 管理控制台并通过以下网址打开 Amazon S3 控制台:https://console.aws.amazon.com/s3/。
②点击“创建存储桶”,在弹出的页面中依次输入桶名称、区域,点击“创建”,即可完成桶的创建。
1.2 AWS S3的简单操作
- 桶的创建:
//设置服务器区域以及桶名称
Regions clientRegion = RegionsUS_EAST_1;
String bucketName = "BucketName";
//连接AWS S3
AmazonS3 s3Client = AmazonS3ClientBuilder.standard().withCredentials(
new ProfileCredentialsProvider()).withRegion(clientRegion).build();
if (!s3Client.doesBucketExistV2(bucketName)) {
//创建桶
Bucket b=s3Client.createBucket(new CreateBucketRequest(bucketName));
// Verify that the bucket was created by retrieving it and checking its location.
String bucketLocation = s3Client.getBucketLocation(
new GetBucketLocationRequest(bucketName));
System.out.println("Bucket location: " + bucketLocation);
}
- 对象的上传:
//设置服务器所在区域
Regions clientRegion = regions.US_EAST_1;
//设置桶名称
String bucketName = "BucketName";
//设置文件名
String fileObjKeyName = "FileName";
//设置文件路径
String filePath="FilePath";
//文件上传路径为文件枯井+文件名
String fileObjectName = filePath+"\\"+fileObjKeyName;
try {
//连接S3
AmazonS3 s3Client = AmazonS3ClientBuilder.standard()
.withRegion(clientRegion)
.withCredentials(new ProfileCredentialsProvider())
.build();
PutObjectRequest request = new PutObjectRequest(bucketName, fileObjKeyName,
new File(fileName));
// ObjectMetadata metadata = new ObjectMetadata();
// metadata.setContentType("plain/text");
// metadata.addUserMetadata("x-amz-meta-title", "someTitle");
// request.setMetadata(metadata);
//上传文件对象
s3Client.putObject(request.**withCannedAcl(CannedAccessControlList.PublicRead)**);
}
注意:withCannedAcl(CannedAccessControlList.PublicRead)可将新上传的对象设置为公开,以获取对象的永久URL。
3. 对象的下载:
Regions clientRegion = regions.US_EAST_1;
String bucketName = "BucketName";
String fileObjKeyName= "FileName";
S3Object fullObject = null;
try {
//连接S3
AmazonS3 s3Client = AmazonS3ClientBuilder.standard()
.withRegion(clientRegion)
.withCredentials(new ProfileCredentialsProvider())
.build();
//获取对象
fullObject = s3Client.getObject(new GetObjectRequest(bucketName, fileObjKeyName));
// System.out.println("Content-Type: " +fullObject.getObjectMetadata().getContentType());
// System.out.println("Content: ");
// displayTextInputStream(fullObject.getObjectContent());
}
catch(AmazonServiceException e) {
e.printStackTrace();
}
catch(SdkClientException e) {
e.printStackTrace();
}
finally {
// To ensure that the network connection doesn't remain open, close any open input streams.
if(fullObject != null) {
fullObject.close();
}
}
此即AWS S3的简单操作