我正在寻找从我的移动应用程序(前端)上传视频和图像的服务。我听说过Amazon S3和CloudFront。我正在寻找一种能够存储它们的服务,并且还能够检查它们是否符合某些标准(例如,每张图片的最大文件大小为3MB),如果文件不符合则向客户端返回错误标准。 Amazon S3或CloudFront是否提供此功能?如果没有,是否还有其他推荐的服务?
答案 0 :(得分:2)
您可以使用AWS SDK。下面是Java版本的示例(亚马逊提供不同语言的SDK):
/**
* It stores the given file name in S3 and returns the key under which the file has been stored
* @param resource
* @param bucketName
* @return
*/
public String storeProfileImage(File resource, String bucketName, String username) {
String resourceUrl = null;
if (!resource.exists()) {
throw new IllegalArgumentException("The file " + resource.getAbsolutePath() + " doesn't exist");
}
long lengthInBytes = resource.length();
//For demo purposes. You should use a configurable property for the max size
if (lengthInBytes > (3 * 1024)) {
//Your error handling here
}
AccessControlList acl = new AccessControlList();
acl.grantPermission(GroupGrantee.AllUsers, Permission.Read);
String key = username + "/profilePicture." + FilenameUtils.getExtension(resource.getName());
try {
s3Client.putObject(new PutObjectRequest(bucketName, key, resource).withAccessControlList(acl));
resourceUrl = s3Client.getResourceUrl(bucketName, key);
} catch (AmazonClientException ace) {
LOG.error("A client exception occurred while trying to store the profile" +
" image {} on S3. The profile image won't be stored", resource.getAbsolutePath(), ace);
}
return resourceUrl;
}
您还可以执行其他操作,例如在存储图像之前检查存储桶是否存在
/**
* Returns the root URL where the bucket name is located.
* <p>Please note that the URL does not contain the bucket name</p>
* @param bucketName The bucket name
* @return the root URL where the bucket name is located.
*/
public String ensureBucketExists(String bucketName) {
String bucketUrl = null;
try {
if (!s3Client.doesBucketExist(bucketName)) {
LOG.warn("Bucket {} doesn't exists...Creating one");
s3Client.createBucket(bucketName);
LOG.info("Created bucket: {}", bucketName);
}
bucketUrl = s3Client.getResourceUrl(bucketName, null) + bucketName;
} catch (AmazonClientException ace) {
LOG.error("An error occurred while connecting to S3. Will not execute action" +
" for bucket: {}", bucketName, ace);
}
return bucketUrl;
}