.NET AWS S3存储操作类

背景:我们是公司内部搭建的存储 并不是使用公网云,可供参考

1、Nuget包  AWSSDK.S3

2、创建一个单利模式 操作类

using Amazon.S3;
using Amazon.S3.Model;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace H3C.AtendanceService.Common
{
    public class AWSS3Helper
    {
        private static AmazonS3Client _s3Client = null;
        private static readonly object _locker = new object();
        private static readonly string _accessKey = "s3的acesskey";
        private static readonly string _secretKey = "s3的secretKey";
        private static readonly string _s3url = "S3的host地址";//要带HTTP或者HTTPS
        private static AWSS3Helper _instance = null;
        private AWSS3Helper()
        {

        }
        /// 
        /// 初始化
        /// 
        /// 
        public static AWSS3Helper GetInStance()
        {
            if (_instance == null)
                lock (_locker)
                    if (_instance == null)
                    {
                        AmazonS3Config config = new AmazonS3Config();
                        config.ServiceURL = _s3url;
                        config.UseHttp = true;//根据实际情况
                        config.ForcePathStyle = true;
                        _s3Client = new AmazonS3Client(
                    _accessKey,
                    _secretKey,
                    config
                    );
                        _instance = new AWSS3Helper();
                    }
            return _instance;
        }

        /// 
        /// 创建Bucket
        /// 
        /// bucketName
        /// 
        /// 
        public async Task CreateBucketAsync(string bucketName, CancellationToken cancellationToken = default)
        {
            if (await CheckBucketExistAsync(bucketName, cancellationToken)) return true;
            var buckectres = await _s3Client.PutBucketAsync(bucketName);
            if (buckectres?.HttpStatusCode == System.Net.HttpStatusCode.OK) return true;
            return false;
        }

        /// 
        /// 创建Bucket
        /// 
        /// bucketName
        /// 
        /// 
        public bool CreateBucket(string bucketName)
        {
            if (CheckBucketExist(bucketName)) return true;
            var buckectres = _s3Client.PutBucket(bucketName);
            if (buckectres?.HttpStatusCode == System.Net.HttpStatusCode.OK) return true;
            return false;
        }

        /// 
        /// 删除Bucket
        /// 
        /// bucketName
        /// 
        /// 
        public async Task DeleteBucketAsync(string bucketName, CancellationToken cancellationToken = default)
        {
            if (!(await CheckBucketExistAsync(bucketName, cancellationToken))) return true;

            var buckectres = await _s3Client.DeleteBucketAsync(bucketName, cancellationToken);
            if (buckectres?.HttpStatusCode == System.Net.HttpStatusCode.OK) return true;
            return false;
        }

        /// 
        /// 删除Bucket
        /// 
        /// bucketName
        /// 
        /// 
        public bool DeleteBucket(string bucketName)
        {
            if (!CheckBucketExist(bucketName)) return true;
            var buckectres = _s3Client.DeleteBucket(bucketName);
            if (buckectres?.HttpStatusCode == System.Net.HttpStatusCode.OK) return true;
            return false;
        }


        /// 
        /// 检测BucketName是否存在
        /// 
        /// bucketName
        /// 线程取消
        /// 
        public async Task CheckBucketExistAsync(string bucketName, CancellationToken cancellationToken = default)
        {
            var response = await _s3Client?.ListBucketsAsync(cancellationToken);
            if (response?.HttpStatusCode == System.Net.HttpStatusCode.OK && response?.Buckets?.Count > 0)
                return response.Buckets.Any(x => x.BucketName == bucketName);
            return false;
        }

        /// 
        /// 检测BucketName是否存在
        /// 
        /// bucketName
        /// 
        public bool CheckBucketExist(string bucketName)
        {
            var response = _s3Client?.ListBuckets();
            if (response?.HttpStatusCode == System.Net.HttpStatusCode.OK && response?.Buckets?.Count > 0)
                return response.Buckets.Any(x => x.BucketName == bucketName);
            return false;
        }

        /// 
        /// 上传文件
        /// 
        /// 文件绝对路径
        /// bucketname
        /// 唯一键值:命名
        /// 目录:目录名/目录名
        /// 是否删除源文件
        /// 线程取消
        /// 
        public async Task UploadFileAsync(string filepath, string bucketname, string filename, string dir = "", bool isDeletedSourceFile = false, CancellationToken cancellationToken = default)
        {
            string key = filename;
            if (!string.IsNullOrEmpty(dir))
            {
                dir = dir.EndsWith("/") ? dir : dir + "/";
                dir = dir.StartsWith("/") ? dir.Substring(1, dir.Length - 1) : dir;
                key = dir + filename;
            }
            PutObjectRequest request = new PutObjectRequest
            {
                BucketName = bucketname,
                Key = key,
                FilePath = filepath,
                CannedACL = S3CannedACL.PublicReadWrite //根据实际情况
            };
            PutObjectResponse response = await _s3Client.PutObjectAsync(request, cancellationToken);
            if (response?.HttpStatusCode == System.Net.HttpStatusCode.OK)
            {
                if (isDeletedSourceFile) File.Delete(filepath);
                return true;
            }
            return false;
        }

        /// 
        /// 上传文件
        /// 
        /// 文件绝对路径
        /// bucketname
        /// 唯一键值:命名
        /// 目录:目录名/目录名
        /// 是否删除源文件
        /// 
        public bool UploadFile(string filepath, string bucketname,string filename, string dir = "", bool isDeletedSourceFile = false)
        {
            string key = filename;
            if (!string.IsNullOrEmpty(dir))
            {
                dir = dir.EndsWith("/") ? dir : dir + "/";
                dir = dir.StartsWith("/") ? dir.Substring(1, dir.Length - 1) : dir;
                key = dir + filename;
            }
            PutObjectRequest request = new PutObjectRequest
            {
                BucketName = bucketname,
                Key = key,
                FilePath = filepath,
                CannedACL = S3CannedACL.PublicReadWrite//根据实际情况

            };
            PutObjectResponse response = _s3Client.PutObject(request);
            if (response?.HttpStatusCode == System.Net.HttpStatusCode.OK)
            {
                if (isDeletedSourceFile) File.Delete(filepath);
                return true;
            }
            return false;
        }

        /// 
        /// 上传文件,返回URL
        /// 
        /// 文件绝对路径
        /// bucketname
        /// 失效时间
        /// 唯一键值:命名
        /// 目录:目录名/目录名
        /// 是否删除源文件
        /// 线程取消
        /// URL
        public async Task UploadFileReturnUrlAsync(string filepath, string bucketname, DateTime expiretime, string filename, string dir = "", bool isDeletedSourceFile = false, CancellationToken cancellationToken = default)
        {
            try
            {
                string key = filename;
                if (!string.IsNullOrEmpty(dir))
                {
                    dir = dir.EndsWith("/") ? dir : dir + "/";
                    dir = dir.StartsWith("/") ? dir.Substring(1, dir.Length - 1) : dir;
                    key = dir + filename;
                }
                PutObjectRequest request = new PutObjectRequest
                {
                    BucketName = bucketname,
                    Key = key,
                    FilePath = filepath,
                    CannedACL = S3CannedACL.PublicReadWrite//根据实际情况
                };
                PutObjectResponse response = await _s3Client.PutObjectAsync(request, cancellationToken);
                if (response?.HttpStatusCode == System.Net.HttpStatusCode.OK)
                {
                    //return GetFileUrl(bucketname, key, expiretime);
                    var url = await GetFileUrlAsync(bucketname, key, expiretime);
                    if (!string.IsNullOrEmpty(url) && isDeletedSourceFile)
                    {
                        File.Delete(filepath);
                        return url;

                    }
                }
                return "";
            }
            catch (Exception ex)
            {

                throw;
            }
        }

        /// 
        /// 上传文件,返回URL
        /// 
        /// 文件绝对路径
        /// bucketname
        /// 失效时间
        /// 唯一键值:命名
        /// 目录:目录名/目录名
        /// 是否删除源文件
        /// 线程取消
        /// URL
        public string UploadFileReturnUrl(string filepath, string bucketname, DateTime expiretime, string filename, string dir = "", bool isDeletedSourceFile = false)
        {
            string key = filename;
            if (!string.IsNullOrEmpty(dir))
            {
                dir = dir.EndsWith("/") ? dir : dir + "/";
                dir = dir.StartsWith("/") ? dir.Substring(1, dir.Length - 1) : dir;
                key = dir + filename;
            }
            PutObjectRequest request = new PutObjectRequest
            {
                BucketName = bucketname,
                Key = key,
                FilePath = filepath,
                CannedACL = S3CannedACL.PublicReadWrite//根据实际情况
            };
            PutObjectResponse response = _s3Client.PutObject(request);
            if (response?.HttpStatusCode == System.Net.HttpStatusCode.OK)
            {
                //return GetFileUrl(bucketname, key, expiretime);
                var url = GetFileUrl(bucketname, key, expiretime);
                if (!string.IsNullOrEmpty(url) && isDeletedSourceFile)
                {
                    File.Delete(filepath);
                    return url;

                }
            }
            return "";
        }

        /// 
        /// 根据key获取URL
        /// 
        /// bucketname
        /// 唯一键值
        /// 失效时间
        /// 
        public async Task GetFileUrlAsync(string bucketname, string key, DateTime expiretime)
        {
            GetPreSignedUrlRequest urlRequest = new GetPreSignedUrlRequest
            {
                BucketName = bucketname,
                Key = key,
                Protocol = Protocol.HTTP,
                Expires = expiretime
            };
            return await Task.Run(() => { return _s3Client.GetPreSignedURL(urlRequest); });
        }

        /// 
        /// 根据key获取URL
        /// 
        /// bucketname
        /// 唯一键值
        /// 失效时间
        /// 
        public string GetFileUrl(string bucketname, string key, DateTime expiretime)
        {
            GetPreSignedUrlRequest urlRequest = new GetPreSignedUrlRequest
            {
                BucketName = bucketname,
                Key = key,
                Protocol = Protocol.HTTP,
                Expires = expiretime
            };
            return _s3Client.GetPreSignedURL(urlRequest);
        }

        /// 
        /// 删除文件
        /// 
        /// bucketname
        /// 唯一键值
        /// 
        /// 
        public async Task DeleteFileAsync(string bucketname, string key, CancellationToken cancellationToken = default)
        {
            DeleteObjectRequest delete = new DeleteObjectRequest
            {
                BucketName = bucketname,
                Key = key
            };
            var deleteObjectResponse = await _s3Client.DeleteObjectAsync(delete, cancellationToken);
            if (deleteObjectResponse?.HttpStatusCode == System.Net.HttpStatusCode.OK) return true;
            return false;
        }

        /// 
        /// 删除文件
        /// 
        /// bucketname
        /// 唯一键值
        /// 
        /// 
        public bool DeleteFile(string bucketname, string key)
        {
            DeleteObjectRequest delete = new DeleteObjectRequest
            {
                BucketName = bucketname,
                Key = key
            };
            var deleteObjectResponse = _s3Client.DeleteObject(delete);
            if (deleteObjectResponse?.HttpStatusCode == System.Net.HttpStatusCode.OK) return true;
            return false;
        }


    }
}

3、使用 

//创建bucket
await AWSS3Helper.GetInStance().CreateBucketAsync("TestBucket");
//
await AWSS3Helper.GetInStance().UploadFileReturnUrlAsync("", buckname, DateTime.Now.AddYears(20), filename,  "Dir/", true);

 

你可能感兴趣的:(C#,.NET,算个技术,aws,s3,.NET,S3,BUCKET,S3存储)