.NET CORE Aws S3 使用

1.安装指定的包

Install-Package AWSSDK.S3 -Version 3.3.104.10

2.使用帮助类

cs 复制代码
using System;
using System.Collections.Generic;
using System.Text;
using Amazon;
using Amazon.Runtime;
using Amazon.S3;
using Amazon.S3.Model;
using System.IO;
using System.Threading.Tasks;

namespace xx.xx.xx.Helper
{
    public class AwsS3Helper
    {
        /// <summary>
        /// 地区是亚太香港
        /// </summary>
        readonly RegionEndpoint bucketRegion = RegionEndpoint.GetBySystemName("xx");


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


        /// <summary>
        /// 请求S3的凭据
        /// </summary>
        readonly AWSCredentials awsCredentials = new BasicAWSCredentials(Appsettings.GetNode("AwsAccessKey"), Appsettings.GetNode("AwsSecretKey"));


        /// <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 key, string contenttype)
        {
            //string key = string.Format("resource/img/{0}/{1}", _resourceType.ToString().Replace("Img", ""), filename);
            try
            {
                var putRequest1 = new PutObjectRequest
                {
                    BucketName = bucketName,
                    //创建对象时,要指定键名,它在存储桶中唯一地标识该对象
                    Key = key,
                    CannedACL = S3CannedACL.PublicRead,//放开存储
                    InputStream = inputStream,
                    ContentType = contenttype
                };
                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
    {
        xx,
        xx,
        xx,
        xx,
        xx,
        xx,
        xx,
        xx
    }
}

3.接口请求

cs 复制代码
 [HttpPost]
        [Route("uploadfils")]
        public async Task<ActionResult<Result>> UploadFiles(List<IFormFile> files, [FromQuery] int type, string filetype)
        {
            var rtype = new ResourceType();
            AwsS3Helper awss3 = new AwsS3Helper(rtype);
            try
            {
                if (files == null && files.Count == 0)
                {
                    return ApiResultHelper.renderError("未选择上传的文件!");
                }
                foreach (var file in files)
                {
                    if (file.Length > 0)
                    {
                        using (var stream = file.OpenReadStream())
                        {
                            var fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
                            //拼接地址
                            string key = string.Format("resource/{0}/{1}/{2}", filetype, "xx", fileName);
                            var result = await awss3.WritingAnObjectByStreamAsync(stream, key, file.ContentType);
                        }
                    }
                }
                return ApiResultHelper.renderSuccess();
            }
            catch (Exception e)
            {
                return ApiResultHelper.renderError();
            }
        }
        /// <summary>
        /// 删除aws s3数据
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("deletefiles")]
        public async Task<ActionResult<Result>> DeleteFiles(string key)
        {
            var rtype = new ResourceType();
            AwsS3Helper awss3 = new AwsS3Helper(rtype);
            try
            {
                if (!string.IsNullOrEmpty(key))
                {
                    var result = await awss3.DeleteAnObjectAsync(key);
                    if (result)
                    {
                        return ApiResultHelper.renderSuccess(true);
                    }
                }
                return ApiResultHelper.renderError();
            }
            catch (Exception e)
            {
                return ApiResultHelper.renderError();
            }
        }
相关推荐
亚林瓜子4 小时前
AWS EC2源代码安装valkey命令行客户端
redis·云计算·aws·cli·valkey
Johny_Zhao6 小时前
K8S+nginx+MYSQL+TOMCAT高可用架构企业自建网站
linux·网络·mysql·nginx·网络安全·信息安全·tomcat·云计算·shell·yum源·系统运维·itsm
大G哥14 小时前
实战演练:用 AWS Lambda 和 API Gateway 构建你的第一个 Serverless API
云原生·serverless·云计算·gateway·aws
weixin_3077791316 小时前
使用FastAPI微服务在AWS EKS中构建上下文增强型AI问答系统
人工智能·python·云计算·fastapi·aws
是垚不是土1 天前
Kolla-Ansible搭建与扩容OpenStack私有云平台
linux·运维·服务器·云计算·ansible·openstack
同聘云1 天前
阿里云ddos云防护服务器有哪些功能?ddos防御手段有哪些??
服务器·阿里云·云计算·ddos
Cloud Traveler1 天前
云计算中的虚拟化:成本节省、可扩展性与灾难恢复的完美结合
云计算
低代码布道师1 天前
腾讯云低代码实战:零基础搭建家政维修平台
低代码·云计算·腾讯云
编程乐趣2 天前
基于.Net Core开发的GraphQL开源项目
后端·.netcore·graphql
wzx_Eleven2 天前
【论文阅读】Efficient and secure federated learning against backdoor attacks
论文阅读·人工智能·机器学习·云计算