.NET Amazon S3

  • 245
  • 0

翻了不少網頁,做個筆記。

首先,先裝 amazon提供的 SDK吧! http://aws.amazon.com/tw/sdk-for-net/
我是選下載安裝檔,然後 VS新增專案就有範例程式可以參考。

然後認證就卡關了 Orz 
不推薦程式裡直接存取 aws_access_key_id、aws_secret_access_key,改用 config也是很合理,網頁例子:

<configuration>
  <configSections>
<!--<section name="aws" type="Amazon.AWSSection, AWSSDK"/> 不能跑 -->
    <section name="aws" type="Amazon.AWSSection, AWSSDK.Core"/>
  </configSections>
<!--<aws profileName="development"/> -->
  <aws profileName="xxx" region="us-west-2" profilesLocation="C:\xxx"/>
</configuration>

接下來,上傳檔案,單純上傳檔案沒什麼問題,在權限卡了一下,希望能透過連結直接分享檔案

using (client = new AmazonS3Client())
{
    GetPreSignedUrlRequest request1 = new GetPreSignedUrlRequest()
    {// 上傳檔案權限不改,只能透過這裡產生的 url取得
        BucketName = bucketName,
        Key = "test", // file name
        Expires = DateTime.Now.AddMinutes(3)
    };
    string url = client.GetPreSignedURL(request1);
    // url like: https://s3-us-west-2.amazonaws.com/_bucketName_/test?AWSAccessKeyId=___&Expires=___&Signature=___

    var mresponse = client.PutObject(new PutObjectRequest
    {// 上傳檔案權限開放任何人都可讀取
        BucketName = bucketName,
        FilePath = @"C:\xxx.txt",
        Grants = new List<S3Grant>() { 
            new S3Grant()
            {
                Permission = S3Permission.READ,
                Grantee = new S3Grantee { URI = "http://acs.amazonaws.com/groups/global/AllUsers" } 
                // 這個找了一陣子… http://docs.aws.amazon.com/AmazonS3/latest/dev/acl-overview.html
            }
        },
        Key = "test",
    });
    // url https://s3-us-west-2.amazonaws.com/_bucketName_/test
    // or: http://_bucketName_.s3-us-west-2.amazonaws.com/test , bucketName放在 host當然就不能走 https
}

嗯…怎麼一下又寫完了,大概就這樣吧。