[ AWS ] Android無法上傳檔案到S3 + AWS S3設定

因為我們公司有遇到新建立一個Bucket

但無論怎麼嘗試, 就是無法將檔案傳上去
只有這個錯誤訊息
Unable to execute HTTP request: Write error: ssl=0xb89d5410: I/O error during system call

後來在google中發現一篇
To do this when creating the S3 client used in the Transfer Utility,
pass a 3rd argument as below

##################################

ClientConfiguration conf = new ClientConfiguration();

AmazonS3Client s3 = new AmazonS3Client(CREDENTIALS, conf, new ApacheHttpClient(conf));

##################################

用這個方法可以找出真正的錯誤訊息

後來得到錯誤訊息為
The bucket you are attempting to access must be addressed using the specified endpoint

意思是我的Bucket所在的Region跟我Android code產生的AWSS3Client的Region不吻合
所以會造成此錯誤

解決方式就是在Android Code中設定endpoint

# 裡面是Bucket所在的地區
s3.setEndpoint("s3-us-west-2.amazonaws.com");
就解決囉!

基本上S3的設定不難
創立完Bucket之後就是

  • 設定Permission
    • Any Authenticated AWS User允許上傳/刪除/取得列表
  • 設定Static Web Hosting
    • 在index document那裡直接隨便打個index.html就可以過了
如果是使用Web要上傳的話記得要額外用IAM建立一個User,然後給予適當的權限就好
如果用Mobile, 就要使用identity pool去產生一組id
然後AWS會自動幫你產生IAM Roles的兩個角色

  • authUser
    • Managed Policy要設定S3 ReadAccessOnly
  • unAuthUser
    • Managed Policy不用設定
    • inline Policy要額外自訂

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "mobileanalytics:PutEvents",
                "cognito-sync:*",
                "cognito-identity:*"
            ],
            "Resource": [
                "*"
            ]
        },
        {
            "Effect": "Allow",
            "Action": [
                "s3:PutObject",
                "s3:GetObject"
            ],
            "Resource": [
                "arn:aws:s3:::bucketName/${cognito-identity.amazonaws.com:sub}/*"
            ]
        }
    ]
}
設定Static Web Hosting可以透過Router53轉成比較好記的網址
這個網址可以再透過CDN (Content Delivery Network) 去節省流量
但千萬要記得, bucketName最好要帶有自己的網域
假設我的網域是xxx.io, 那我bucketName最好就是類似images.xxx.io
因為AWS的static web hosting的開頭必須是自己的bucketName
推薦使用cloudflare, 一開始可以使用免費方案
相關設定Google上很多, 所以可以自行參考, 不多加贅述囉


留言

這個網誌中的熱門文章

[翻譯] 介紹現代網路負載平衡與代理伺服器

[MySQL] schema 與資料類型優化