最近在用aws的s3做云存储,把文件上传上去,在数据库中记录对应的url,下面是示例代码:
public static String uploadToS3(File tempFile, String remoteFileName) throws IOException {
PropertiesUtil propertiesUtil = new PropertiesUtil("");
//首先创建一个s3的客户端操作对象(需要amazon提供的密钥)
AmazonS3 s3 = new AmazonS3Client(
new BasicAWSCredentials((Consts.S3_ACCESS_KEY),
(Consts.S3_SCERET_KEY)));
Region usWest2 = (Regions.US_WEST_2);
(usWest2);
//设置bucket,key
String bucketName = Consts.S3_BUCKET_NAME;
String key = () + ".apk";
try {
//验证名称为bucketName的bucket是否存在,不存在则创建
if (!checkBucketExists(s3, bucketName)) {
(bucketName);
}
//上传文件
(new PutObjectRequest(bucketName, key, tempFile));
S3Object object = (new GetObjectRequest(bucketName, key));
//获取一个request
GeneratePresignedUrlRequest urlRequest = new GeneratePresignedUrlRequest(
bucketName, key);
Date expirationDate = null;
try {
expirationDate = new SimpleDateFormat("yyyy-MM-dd").parse("2020-12-31");
} catch (Exception e) {
();
}
//设置过期时间
(expirationDate);
//生成公用的url
URL url = (urlRequest);
("=========URL=================" + url + "============URL=============");
if (url == null) {
throw new OperateFailureException("can't get s3 file url!");
}
return ();
} catch (AmazonServiceException ase) {
();
("====================================AWS S3 UPLOAD ERROR START======================================");
("Caught an AmazonServiceException, which means your request made it "
+ "to Amazon S3, but was rejected with an error response for some reason.");
("Caught an AmazonServiceException, which means your request made it "
+ "to Amazon S3, but was rejected with an error response for some reason.");
("Error Message: " + ());
("HTTP Status Code: " + ());
("AWS Error Code: " + ());
("Error Type: " + ());
("Request ID: " + ());
((), ase);
("====================================AWS S3 UPLOAD ERROR END======================================");
throw new OperateFailureException("error occurs during upload to s3!");
} catch (AmazonClientException ace) {
("====================================AWS S3 UPLOAD ERROR START======================================");
("Caught an AmazonClientException, which means the client encountered "
+ "a serious internal problem while trying to communicate with S3, "
+ "such as not being able to access the network.");
("Error Message: " + ());
("====================================AWS S3 UPLOAD ERROR END======================================");
throw new OperateFailureException("error occurs during upload to s3!");
}
}
/**
* 验证s3上是否存在名称为bucketName的Bucket
* @param s3
* @param bucketName
* @return
*/
public static boolean checkBucketExists (AmazonS3 s3, String bucketName) {
List<Bucket> buckets = ();
for (Bucket bucket : buckets) {
if (((), bucketName)) {
return true;
}
}
return false;
}
上面的代码只是一部分,整个过程是在jsp页面吧文件上传到后台,后台创建一个临时文件,把临时文件上传到s3上,并获取一个可以下载文件的url;
这里是一个英文的参考:/docs/master/radosgw/s3/java/