欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2023-08-21 20:06:46
一. 上传示例 Amazon Simple Storage Service 是互联网存储解决方案。该服务旨在降低开发人员进行网络规模级计算的难度。 Amazon S3 提供了一个简单 Web 服务接口,可用于随时在 Web 上的任何位置存储和检索任何数量的数据。此服务让所有开发人员都能访问同一个具备 ......

一.  上传示例

  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)
    }
}

 

   如下所示:

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

 

  参考文献: 

    
    https://docs.aws.amazon.com/zh_cn/amazons3/latest/dev/uploadobjsingleopnet.html