只有累積,沒有奇蹟

2018年12月20日 星期四

[AWS] 使用 AWS SDK上傳檔案到 AWS S3

前言
最近在與第三方做串接時有個需求是要將圖片存起來放在 Application Server 上,與同事討論建議將圖片放在AWS S3 上,多年前有微軟剛推出 Azure 時有接觸過一些,但這幾年隨著年紀增長早已忘光光,這篇簡單紀錄 C# 透過 AWS SDK 將圖片上傳到 AWS S3 上的步驟與要注意的細節

AWS S3 
Amazon Simple Storage Service 功能簡稱 S3,是Amazon的物件儲存服務主要提供使用者存放 Data 像是 html, css, js...等靜態檔案,上傳前需要建立儲存體 (Buckets) 來存放需要放在的物件接著透過 AWS Manager Console 的後台服務上傳物件到雲端上,使用者就可以透過 S3 的服務讀取到上傳的資料,如下圖所示

安裝 AWS SDK 
除了可以透過 AWS Manager Console 後台上傳檔案AWS 也提供 SDK 讓開發者可以透過 API 來上傳儲存的物件,在 .NET 有兩種方式可以安裝此套件
1. 可以到 nuget 主控台 輸入下列指令下載 AWS SDK 套件
Install-Package AWSSDK -Version 2.3.55.2
2. 到 nuget 管理員輸入 AWSSDK 直接下載

設定 Config Key
在 Application Config 中設定 AccessKey , SecretKey

使用 AWS SDK 上傳物件到 S3
參考 開發人員指南 上傳 Code 如下
  1. using System;
  2. using System.Threading.Tasks;
  3. using Amazon.S3;
  4. using Amazon.S3.Transfer;
  5. using Amazon;
  6. using Amazon.S3.Model;
  7.  
  8. namespace AWS
  9. {
  10. class blog
  11. {
  12. private const string bucketName = "your bucketName";
  13. private const string keyName = "Test.png";
  14. private const string filePath = @"D:\Test.png";
  15. private static readonly RegionEndpoint bucketRegion = RegionEndpoint.APNortheast1;
  16. private static IAmazonS3 s3Client;
  17.  
  18. static void Main(string[] args)
  19. {
  20. s3Client = new AmazonS3Client(bucketRegion);
  21.  
  22. try
  23. {
  24. PutObjectRequest ObjectRequest = new PutObjectRequest
  25. {
  26. BucketName = bucketName,
  27. FilePath = filePath,
  28. Key = keyName,
  29. CannedACL = S3CannedACL.PublicRead
  30. };
  31.  
  32. // upload object
  33. PutObjectResponse myResponse = s3Client.PutObject(ObjectRequest);
  34. }
  35. catch (AmazonS3Exception e)
  36. {
  37. Console.WriteLine("Error encountered on server. Message:'{0}' when writing an object", e.Message);
  38. }
  39. catch (Exception e)
  40. {
  41. Console.WriteLine("Unknown encountered on server. Message:'{0}' when writing an object", e.Message);
  42. }
  43. }
  44. }
  45. }
  46.  
程式說明 : 
  • Line 12 : 要上傳到的 bucket Name 儲存體
  • Line 13 : 要上傳到的位置 + 檔名 , 舉例 : 可以透過目錄區分物件 public / test / test.jpg
  • Line 14 : 上傳物件路徑 
  • Line 15 : 定義 RegionEndpoint , 在一開始建立 bucket 會設定機房的位置 (參考備註)
  • Line 20 : 初始化 s3Client 物件 透過建構子定義 Endpoint
  • Line 24 : 初始化要上傳的物件 putObjectRequest,設定要上傳到的 bucketName 物件路徑 與 設定此物件為公開 (非必要)
  • Line 24 : 使用 putObject 方法上傳物件
使用 AWS SDK 上傳物件到 S3 (非同步)
如果在開發上是有非同步的需求,可以參考下面
  1. using System;
  2. using System.Threading.Tasks;
  3. using Amazon.S3;
  4. using Amazon.S3.Transfer;
  5. using Amazon;
  6.  
  7. namespace AWS
  8. {
  9. class blog
  10. {
  11. private const string bucketName = "urbucketName";
  12. private const string filePath = @"D:\Test.png";
  13. // Specify your bucket region (an example region is shown).
  14. private static readonly RegionEndpoint bucketRegion = RegionEndpoint.APNortheast1;
  15. private static IAmazonS3 s3Client;
  16.  
  17. static void Main(string[] args)
  18. {
  19. s3Client = new AmazonS3Client(bucketRegion);
  20. UploadFileAsync().Wait();
  21. }
  22.  
  23. private static async Task UploadFileAsync()
  24. {
  25. try
  26. {
  27. var fileTransferUtility = new TransferUtility(s3Client);
  28. await fileTransferUtility.UploadAsync(filePath, bucketName);
  29.  
  30. Console.WriteLine("上傳完成");
  31. }
  32. catch (AmazonS3Exception e)
  33. {
  34. Console.WriteLine("Error encountered on server. Message:'{0}' when writing an object", e.Message);
  35. }
  36. catch (Exception e)
  37. {
  38. Console.WriteLine("Unknown encountered on server. Message:'{0}' when writing an object", e.Message);
  39. }
  40. }
  41. }
  42. }
  43.  
程式說明 : 
  • Line 27 : 初始化 TransferUtility 物件 透過建構子定義 Endpoint
  • Line 28 : 透過 TransferUtility 的 UploadAsync 方法上傳物件到 S3 上
補充
在定義 BucketRegion 需特別注意要指定到你一開始建立的機房位置,如果指定錯誤的話會出現
Error encountered on server. Message:'The bucket you are attempting to access must be addressed using the specified endpoint. Please send all future requests to this endpoint.' when writing an object ? 
建立位置與對應 EndPoint 可以參考官方 AWS Regions and Endpoints 說明,避免踩雷 XDDD

參考
Amazon S3 Features
Upload a File to an S3 Bucket Using the AWS SDK for .NET (High-Level API)
使用AWS SDK for .NET
Build a Serverless Web Application

Related Posts:

  • [Nuget] The term 'nuget.exe' is not recognized as the name of a cmdlet, function, script file, or operable program問題  最接開發完 Libary 專案要上傳到 nuget server 時,要將 package 檔案透過指令 push 噴 error 錯誤訊息 nuget.exe : The term 'nuget.exe' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the … Read More
  • [Nuget] Nuget operation failed前言     為了取得/建置專案的方便,最近常遇到同事透過 powershell 指令使用svn取得最新的代碼並呼叫MSBuild自動建置專案,今天在執行完前同事所撰寫的 powershell script 後開啟專案跳出 Nuget operation failed 提示訊提,這種情況還是第一次遇到,新筆電與桌基平常都正常來記錄處理臭蟲的過程 症狀 開啟Visual Studio 2017跳出錯誤訊息:Nuget o… Read More
  • [Nuget] 使用 NuGet Package Explorer 製作 Nuget 套件問題  在上一篇介紹了如何架設公司內部 nuger server,架設完畢後會使用 nuget push 指令將開發完 Library 上傳到公司內部 nuget server 上,但每次都要透過手動打指令 push 難道沒有更快的方法了嗎 ? 今天就要來介紹一套好用的工具 Nuget Package Explorer 可以省去打指令的動作,透過 GUI 的介面將開發好的 Library 上傳到共用或是私人架設的 nuget … Read More
  • [AWS] 使用 AWS SDK上傳檔案到 AWS S3前言 最近在與第三方做串接時,有個需求是要將圖片存起來放在 Application Server 上,與同事討論建議將圖片放在AWS S3 上,多年前有微軟剛推出 Azure 時有接觸過一些,但這幾年隨著年紀增長早已忘光光,這篇簡單紀錄 C# 透過 AWS SDK 將圖片上傳到 AWS S3 上的步驟與要注意的細節 AWS S3  Amazon Simple Storage Service 功能簡稱 S3,是Amazon的物件儲存服務,… Read More
  • [Nuget] 架設公司內部 Nuget Server 前言  在開發上常常會遇到某些代碼是跨專案共用的,在 .NET 中會將重複使用的代碼打包成「套件」,其中包含了編譯後的 dll 以及相關的檔案資訊,接著將套件內容上傳到 Nuget Server 上提供開發者下載使用,Nuget server 有分共用與私人主機兩種,共用的 nuget server 上有相當多好用的 libary 供開發者下載,例如常用的 NLog、newtonsoft.json、NUnit...等各種好用的 pack… Read More

0 意見:

張貼留言

Copyright © 2025 m@rcus 學習筆記 | Powered by Blogger

Design by Anders Noren | Blogger Theme by NewBloggerThemes.com