1. 程式人生 > >asp.net core系列 69 Amazon S3 資原始檔上傳示例

asp.net core系列 69 Amazon S3 資原始檔上傳示例

一.  上傳示例

  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

&n