asp.net core系列 69 Amazon S3 资源文件上传示例

一.  上传示例

  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
{

    /// 
    ///Amazon S3 上传数据(照片、视频、文档等) 
    /// 
    public class AwsS3Helper
    {

        /// 
        /// 地区是亚太香港
        /// 
        readonly RegionEndpoint bucketRegion = RegionEndpoint.GetBySystemName("ap-east-1");


        /// 
        /// 要向 Amazon S3 上传数据(照片、视频、文档等),
        /// 您必须首先在其中一个 AWS 区域中创建 S3 存储桶, 比如:在亚太香港地址,创建了一个gfbk桶
        /// 然后,您可以将任何数量的对象上传到该存储桶。
        /// 每个 AWS 账户中创建多达 100 个存储桶,一个存储桶中可以存储任意数量的对象。
        /// 资料:https://docs.aws.amazon.com/zh_cn/AmazonS3/latest/dev/UsingBucket.html
        /// 
        readonly string bucketName = Constants.bucketName;


        /// 
        /// 请求S3的凭据
        /// 
        readonly AWSCredentials awsCredentials = new BasicAWSCredentials(Constants.accessKey, Constants.secretKey);


        /// 
        /// 请求客户端
        /// 
        AmazonS3Client client = null;


        /// 
        /// 上传资源类型
        /// 
        ResourceType _resourceType;

        public AwsS3Helper(ResourceType resourceType)
        {
            _resourceType = resourceType;
            client = new AmazonS3Client(awsCredentials, bucketRegion);
        }


        /// 
        ///创建一个桶
        /// 
        /// 
        public async Task CreateBucket()
        {
            var putBucketRequest = new PutBucketRequest
            {
                BucketName = bucketName,
                UseClientRegion = true
            };
            PutBucketResponse putBucketResponse = await client.PutBucketAsync(putBucketRequest);
            string bucketLocation = await FindBucketLocationAsync(client);
        }


        /// 
        /// 查找桶所在的地区
        /// 
        /// 
        /// 
        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;
        }



        /// 
        /// 上传文件
        /// 
        /// 上传的文件地址如:E:\test.jpg
        /// 
        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{
                                    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));
            }
        }



        /// 
        /// 上传文件 (未经测试)
        /// 
        /// 以流的形式
        /// 
        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));
            }
        }


        /// 
        /// 删除一个对象
        /// 
        /// 删除的对象的键如:resource/img/basketballnews/test1.jpg
        /// 
        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));
            }
        }


        /// 
        /// 获取
        /// 
        /// 限制对以指定前缀开头的键的响应
        /// 
        public async Task> 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)
    }
}

 

   如下所示:

asp.net core系列 69 Amazon S3 资源文件上传示例_第1张图片

 

  参考文献: 

    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

 

你可能感兴趣的:(asp.net core系列 69 Amazon S3 资源文件上传示例)