2016-04-18 121 views
0

我正在尋找一項服務來從我的移動應用程序(前端)上傳視頻和圖像。我聽說過Amazon S3和CloudFront。我正在尋找將存儲它們的服務,並且還能夠檢查它們是否符合特定條件(例如,每張圖片的最大文件大小爲3MB),並且如果文件不符合,則會向客戶端返回錯誤標準。 Amazon S3或CloudFront是否提供此功能?如果沒有,有沒有其他推薦的服務呢?將圖像和視頻上傳到(S3,CloudFront等)的服務

回答

2

您可以使用AWS開發工具包。這裏如下(Amazon提供的SDK不同語言)的Java版本爲例:

/** 
* 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; 
} 
+0

非常感謝。你有沒有試過filestack.com? –

+0

不,我是亞馬遜網絡服務的粉絲:-)哦,順便說一句,你在問關於CloudFront。 CloudFront是一個內容分發網絡(CDN)。因此,只要將文件放到S3存儲桶中,然後創建使用該存儲桶的CF分配,就會將內容從最近的位置提供給用戶。 –