我使用Java SDK将项目上传到Amazon S3
。我上传的一些项目需要公开,我可以通过公共URL访问,而其他一些项目需要是私有的。请检查以下代码。
public class FileUpload {
public static int PUBLIC = 1;
public static int PRIVATE = 2;
public void UploadObjectSingleOperation(String bucketName, InputStream inputStream, String fileName, int privacy) {
String keyName = "xxxxxxxxxxx";
String secret = "xxxxxxxxxxxxxxxxxxxxxxxxx";
BasicAWSCredentials creds = new BasicAWSCredentials(keyName, secret);
AmazonS3 s3client=null;
if(privacy==PUBLIC)
{
s3client = AmazonS3ClientBuilder.standard().withCredentials(new AWSStaticCredentialsProvider(creds)).withRegion(Regions.AP_SOUTH_1).build();
}
else if(privacy==PRIVATE)
{
s3client = AmazonS3ClientBuilder.standard().withCredentials(new AWSStaticCredentialsProvider(creds)).build();
}
try {
System.out.println("Uploading a new object to S3 from a file\n");
s3client.putObject(new PutObjectRequest(bucketName, fileName, inputStream,null).withCannedAcl(CannedAccessControlList.PublicRead));
} catch (AmazonServiceException ase) {
System.out.println("Caught an AmazonServiceException, which "
+ "means your request made it "
+ "to Amazon S3, but was rejected with an error response"
+ " for some reason.");
System.out.println("Error Message: " + ase.getMessage());
System.out.println("HTTP Status Code: " + ase.getStatusCode());
System.out.println("AWS Error Code: " + ase.getErrorCode());
System.out.println("Error Type: " + ase.getErrorType());
System.out.println("Request ID: " + ase.getRequestId());
} catch (AmazonClientException ace) {
System.out.println("Caught an AmazonClientException, which "
+ "means the client encountered "
+ "an internal error while trying to "
+ "communicate with S3, "
+ "such as not being able to access the network.");
System.out.println("Error Message: " + ace.getMessage());
}
}
}
对于私有对象,我如何获得安全URL,如“标记化”URL?这意味着,URL存在,但它需要一些特殊的验证来“工作”或“允许访问”,所以不是每个人都可以访问URL但我的应用程序。我怎么能这样做?
我在S3查看了Signed URLs
,但它只设置了到期日期/时间。我的URL不需要过期,但需要一些访问验证。
答案 0 :(得分:0)
上传到s3后,您需要使用s3client通过存储桶/密钥为对象请求预先签名的URL。
预签名网址的有效期最长为七天,因为您在签名计算中使用的签名密钥有效期最长为七天。
AWS文档有一个关于如何generate these urls from java:
的示例AmazonS3 s3client = new AmazonS3Client(new ProfileCredentialsProvider());
java.util.Date expiration = new java.util.Date();
long msec = expiration.getTime();
msec += 1000 * 60 * 60; // 1 hour.
expiration.setTime(msec);
GeneratePresignedUrlRequest generatePresignedUrlRequest =
new GeneratePresignedUrlRequest(bucketName, objectKey);
generatePresignedUrlRequest.setMethod(HttpMethod.GET); // Default.
generatePresignedUrlRequest.setExpiration(expiration);
URL s = s3client.generatePresignedUrl(generatePresignedUrlRequest);