asp.net core系列 69 Amazon S3 資源文件上傳示例

  • 2019 年 10 月 3 日
  • 筆記

一.  上傳示例

  Amazon Simple Storage Service 是互聯網存儲解決方案。該服務旨在降低開發人員進行網絡規模級計算的難度。

  Amazon S3 提供了一個簡單 Web 服務接口,可用於隨時在 Web 上的任何位置存儲和檢索任何數量的數據。此服務讓所有開發人員都能訪問同一個具備高擴展性、可靠性、安全性和快速價廉的數據存儲基礎設施, Amazon 用它來運行其全球的網站網絡。此服務旨在為開發人員帶來最大化的規模效益。

  Install-Package AWSSDK.S3 -Version 3.3.104.10

using Amazon;  using Amazon.Runtime;  using Amazon.S3;  using Amazon.S3.Model;  using System;  using System.Collections.Generic;  using System.IO;  using System.Text;  using System.Threading.Tasks;    /*       //上傳籃球資料圖片       AwsS3Helper s3 = new AwsS3Helper(ResourceType.basketballnewsImg);       s3.WritingAnObjectAsync("E:\11\test1.jpg").Wait();   */  namespace AwsS3WithNetCore  {        /// <summary>      ///Amazon S3 上傳數據(照片、視頻、文檔等)      /// </summary>      public class AwsS3Helper      {            /// <summary>          /// 地區是亞太香港          /// </summary>          readonly RegionEndpoint bucketRegion = RegionEndpoint.GetBySystemName("ap-east-1");              /// <summary>          /// 要向 Amazon S3 上傳數據(照片、視頻、文檔等),          /// 您必須首先在其中一個 AWS 區域中創建 S3 存儲桶, 比如:在亞太香港地址,創建了一個gfbk桶          /// 然後,您可以將任何數量的對象上傳到該存儲桶。          /// 每個 AWS 賬戶中創建多達 100 個存儲桶,一個存儲桶中可以存儲任意數量的對象。          /// 資料:https://docs.aws.amazon.com/zh_cn/AmazonS3/latest/dev/UsingBucket.html          /// </summary>          readonly string bucketName = Constants.bucketName;              /// <summary>          /// 請求S3的憑據          /// </summary>          readonly AWSCredentials awsCredentials = new BasicAWSCredentials(Constants.accessKey, Constants.secretKey);              /// <summary>          /// 請求客戶端          /// </summary>          AmazonS3Client client = null;              /// <summary>          /// 上傳資源類型          /// </summary>          ResourceType _resourceType;            public AwsS3Helper(ResourceType resourceType)          {              _resourceType = resourceType;              client = new AmazonS3Client(awsCredentials, bucketRegion);          }              /// <summary>          ///創建一個桶          /// </summary>          /// <returns></returns>          public async Task CreateBucket()          {              var putBucketRequest = new PutBucketRequest              {                  BucketName = bucketName,                  UseClientRegion = true              };              PutBucketResponse putBucketResponse = await client.PutBucketAsync(putBucketRequest);              string bucketLocation = await FindBucketLocationAsync(client);          }              /// <summary>          /// 查找桶所在的地區          /// </summary>          /// <param name="client"></param>          /// <returns></returns>          private async Task<string> FindBucketLocationAsync(IAmazonS3 client)          {              string bucketLocation;              var request = new GetBucketLocationRequest()              {                  BucketName = bucketName              };              GetBucketLocationResponse response = await client.GetBucketLocationAsync(request);              bucketLocation = response.Location.ToString();              return bucketLocation;          }                /// <summary>          /// 上傳文件          /// </summary>          /// <param name="uploadFilePath">上傳的文件地址如:E:test.jpg</param>          /// <returns></returns>          public async Task<bool> WritingAnObjectAsync(string uploadFilePath)          {              try              {                  string filename = uploadFilePath.Substring(uploadFilePath.LastIndexOf('\')+1);                  string key = string.Format("resource/img/{0}/{1}", _resourceType.ToString().Replace("Img", ""), filename);                  var putRequest2 = new PutObjectRequest                  {                      BucketName = bucketName,                      //獲取和設置鍵屬性。此鍵用於標識S3中的對象,上傳到s3的路徑+文件名,                      //S3上沒有文件夾可以創建一個,參考https://www.cnblogs.com/web424/p/6840207.html                      Key = key,                      //所有者獲得完全控制權,匿名主體被授予讀訪問權。如果                      //此策略用於對象,它可以從瀏覽器中讀取,無需驗證                      CannedACL = S3CannedACL.PublicRead,                      //上傳的文件路徑                      FilePath = uploadFilePath,                      //為對象設置的標記。標記集必須編碼為URL查詢參數                      TagSet = new List<Tag>{                                      new Tag { Key = "Test", Value = "S3Test"} }                      //ContentType = "image/png"                  };                  putRequest2.Metadata.Add("x-amz-meta-title", "AwsS3Net");                  PutObjectResponse response2 = await client.PutObjectAsync(putRequest2);                  return true;              }              catch (AmazonS3Exception e)              {                  throw new Exception(string.Format("Error encountered ***. Message:'{0}' when writing an object", e.Message));              }              catch (Exception e)              {                  throw new Exception(string.Format("Unknown encountered on server. Message:'{0}' when writing an object", e.Message));              }          }                /// <summary>          /// 上傳文件 (未經測試)          /// </summary>          /// <param name="inputStream">以流的形式</param>          /// <returns></returns>          public async Task<bool> WritingAnObjectByStreamAsync(Stream inputStream,string filename)          {              string key = string.Format("resource/img/{0}/{1}", _resourceType.ToString().Replace("Img", ""), filename);              try              {                  var putRequest1 = new PutObjectRequest                  {                      BucketName = bucketName,                      //創建對象時,要指定鍵名,它在存儲桶中唯一地標識該對象                      Key = key,                      InputStream= inputStream                  };                  PutObjectResponse response1 = await client.PutObjectAsync(putRequest1);                  return true;              }              catch (AmazonS3Exception e)              {                  throw new Exception(string.Format("Error encountered ***. Message:'{0}' when writing an object", e.Message));              }              catch (Exception e)              {                  throw new Exception(string.Format("Unknown encountered on server. Message:'{0}' when writing an object", e.Message));              }          }              /// <summary>          /// 刪除一個對象          /// </summary>          /// <param name="key">刪除的對象的鍵如:resource/img/basketballnews/test1.jpg</param>          /// <returns></returns>          public async Task<bool> DeleteAnObjectAsync(string key)          {              try              {                  // 1. Delete object-specify only key name for the object.                  var deleteRequest1 = new DeleteObjectRequest                  {                      BucketName = bucketName,                      Key = key                  };                  DeleteObjectResponse response1 = await client.DeleteObjectAsync(deleteRequest1);                  return true;              }              catch (AmazonS3Exception e)              {                  throw new Exception(string.Format("Error encountered ***. Message:'{0}' when writing an object", e.Message));              }              catch (Exception e)              {                  throw new Exception(string.Format("Unknown encountered on server. Message:'{0}' when writing an object", e.Message));              }          }              /// <summary>          /// 獲取          /// </summary>          /// <param name="prefix">限制對以指定前綴開頭的鍵的響應</param>          /// <returns></returns>          public async Task<List<S3Object>> ListObjectsAsync(string prefix = "")          {              try              {                    var list = new ListObjectsRequest                  {                      BucketName = bucketName,                      Prefix = prefix                  };                    ListObjectsResponse response1 = await client.ListObjectsAsync(list);                    return response1.S3Objects;              }              catch (AmazonS3Exception e)              {                  throw new Exception(string.Format("Error encountered ***. Message:'{0}' when writing an object", e.Message));              }              catch (Exception e)              {                  throw new Exception(string.Format("Unknown encountered on server. Message:'{0}' when writing an object", e.Message));              }          }      }            public enum ResourceType      {          basketballnewsImg,          footballnewsImg,          bannerImg,          videoImg,          logoImg      }        internal class Constants      {          internal const string bucketName = "gfbk";//Write your bucket name          internal const string accessKey = "xxxxxx"; // write your IAM credentials first access key          internal const string secretKey = "xxxxxx"; // write your IAM credentials second access key(secret key)      }  }

 

   如下所示:

 

  參考文獻: 

    https://aws.amazon.com/cn/developer/language/net/code-samples/net-code-samples/
    https://docs.aws.amazon.com/zh_cn/AmazonS3/latest/dev/UploadObjSingleOpNET.html