首页 > 其他分享 >Minio使用(Minio帮助类 3.1.13版本 )

Minio使用(Minio帮助类 3.1.13版本 )

时间:2024-06-14 23:31:38浏览次数:31  
标签:Minio 13 minio 存储 flag bucketName 3.1 Exception string

目录

一、安装部署

二、注册成window服务

三、C#文件上传下载

四、minio文件操作帮助类


一、安装部署

1、下载安装包:MinIO | 高性能,对Kubernetes友好的对象存储

2、放到磁盘中,后面会以这个文件进行服务器安装

3、磁盘新建一个目录用于存放上传文件,比如我创建的为:Data

4、运行控制台程序:切换到安装包所在目录(后面部分为存储路径),

输入命令:minio.exe server D:\\Data

 5、打开浏览器,访问:http://127.0.0.1:9000 用户名和密码默认为:minioadmin,主界面如下

 二、注册成window服务

WinSW(Windows Service Wrapper)是一个工具,可以将任何可执行文件或脚本包装并作为 Windows 服务运行。它特别适用于那些本身不支持作为 Windows 服务运行的应用程序或脚本。

1. 下载winsw,下载地址:Releases · winsw/winsw · GitHub

 2. 将WinSW-net461.exe复制到自定义的目录,并重命名为自己想命名的服务名称minio-server.exe

 3. 同目录下创建minio-server.xml。特别注意,xml和exe必须同名

 4. 配置minio-server.xml文件

 5. 使用minio-server.exe install安装服务

安装服务命令:minio-server.exe install

启动服务命令:minio-server.exe start

停止服务命令:minio-server.exe stop

移除服务命令:sc delete minio-server

xml配置文件如下:

<service>
    <id>minio-server</id>
    <name>minio-server</name>
    <description>minio文件存储服务器</description>
    <!-- 可设置环境变量 -->
    <env name="HOME" value="%BASE%"/>
    <executable>%BASE%\minio.exe</executable>
    <arguments>server "%BASE%\data"</arguments>
    <!-- <logmode>rotate</logmode> -->
    <logpath>%BASE%\logs</logpath>
    <log mode="roll-by-size-time">
      <sizeThreshold>10240</sizeThreshold>
      <pattern>yyyyMMdd</pattern>
      <autoRollAtTime>00:00:00</autoRollAtTime>
      <zipOlderThanNumDays>5</zipOlderThanNumDays>
      <zipDateFormat>yyyyMMdd</zipDateFormat>
    </log>
</service>

三、C#文件上传下载

public async void testupload()
        {
            try
            {
                MinioClient minio = new MinioClient("127.0.0.1:9000", "minioadmin", "minioadmin");
                //桶名称
                string buckName = "202110001";
                //判断桶是否存在,如果不存在则创建桶,否则上传文件会异常
                var exists = await MinioHelper.BucketExists(minio, buckName);
                if (!exists)
                {
                    //创建桶
                    await MinioHelper.MakeBucket(minio, buckName);
                }
                //上传文件(桶下面可以自定义文件夹。如:1027/20211027001.jpg 则会创建一个1027文件夹)
                var result = await MinioHelper.FPutObject(minio, buckName, "1027/20211027001.png", "E:\\202110271417.png");
                //下载文件地址:192.168.90.128:9000+桶名称+文件名称
            }
            catch (Exception ex)
            {
                string str = ex.Message;
            }
        }

四、minio文件操作帮助类

public class MinioHelper
    {

        #region 操作存储桶

        /// <summary>创建存储桶
        /// 创建存储桶
        /// </summary>
        /// <param name="minio">连接实例</param>
        /// <param name="bucketName">存储桶名称</param>
        /// <param name="loc">可选参数</param>
        /// <returns></returns>
        public async static Task<bool> MakeBucket(MinioClient minio, string bucketName, string loc = "us-east-1")
        {
            bool flag = false;
            try
            {
                bool found = await minio.BucketExistsAsync(bucketName);
                if (found)
                {
                    throw new Exception(string.Format("存储桶[{0}]已存在", bucketName));
                }
                else
                {
                    await minio.MakeBucketAsync(bucketName, loc);
                    flag = true;
                }
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }
            return flag;
        }

        /// <summary>列出所有的存储桶
        /// 列出所有的存储桶
        /// </summary>
        /// <param name="minio">连接实例</param>
        /// <returns></returns>
        public async static Task<Tuple<bool, Minio.DataModel.ListAllMyBucketsResult>> ListBuckets(MinioClient minio)
        {
            bool flag = false;
            var list = new Minio.DataModel.ListAllMyBucketsResult();
            try
            {
                list = await minio.ListBucketsAsync();
                flag = true;
                //foreach (var bucket in list.Buckets)
                //{
                //    Console.WriteLine($"{bucket.Name} {bucket.CreationDateDateTime}");
                //}
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }
            return Tuple.Create(flag, list);
        }

        /// <summary>检查存储桶是否存在
        /// 检查存储桶是否存在
        /// </summary>
        /// <param name="minio">连接实例</param>
        /// <param name="bucketName">存储桶名称</param>
        /// <returns></returns>
        public async static Task<bool> BucketExists(MinioClient minio, string bucketName)
        {
            bool flag = false;
            try
            {
                flag = await minio.BucketExistsAsync(bucketName);
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }
            return flag;
        }

        /// <summary>删除一个存储桶
        /// 删除一个存储桶
        /// </summary>
        /// <param name="minio">连接实例</param>
        /// <param name="bucketName">存储桶名称</param>
        /// <returns></returns>
        public async static Task<bool> RemoveBucket(MinioClient minio, string bucketName)
        {
            bool flag = false;
            try
            {
                bool found = await minio.BucketExistsAsync(bucketName);
                if (found)
                {
                    await minio.RemoveBucketAsync(bucketName);
                    flag = true;
                }
                else
                {
                    throw new Exception(string.Format("存储桶[{0}]不存在", bucketName));
                }
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }
            return flag;
        }

        /// <summary>列出存储桶里的对象
        /// 列出存储桶里的对象
        /// </summary>
        /// <param name="minio">连接实例</param>
        /// <param name="bucketName">存储桶名称</param>
        /// <param name="prefix">对象的前缀</param>
        /// <param name="recursive">true代表递归查找,false代表类似文件夹查找,以'/'分隔,不查子文件夹</param>
        public static Tuple<bool, IObservable<Item>> ListObjects(MinioClient minio, string bucketName, string prefix = null, bool recursive = true)
        {
            bool flag = false;
            IObservable<Item> observable = null;
            try
            {
                var found = minio.BucketExistsAsync(bucketName);
                if (found.Result)
                {
                    observable = minio.ListObjectsAsync(bucketName, prefix, recursive);
                    flag = true;
                }
                else
                {
                    throw new Exception(string.Format("存储桶[{0}]不存在", bucketName));
                }
                //IDisposable subscription = observable.Subscribe(
                //    item => Console.WriteLine($"Object: {item.Key}"),
                //    ex => Console.WriteLine($"OnError: {ex}"),
                //    () => Console.WriteLine($"Listed all objects in bucket {bucketName}\n"));

            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }
            return Tuple.Create(flag, observable);
        }

        /// <summary>列出存储桶中未完整上传的对象
        /// 列出存储桶中未完整上传的对象
        /// </summary>
        /// <param name="minio">连接实例</param>
        /// <param name="bucketName">存储桶名称</param>
        /// <param name="prefix">对象的前缀</param>
        /// <param name="recursive">true代表递归查找,false代表类似文件夹查找,以'/'分隔,不查子文件夹</param>
        /// <returns></returns>
        public static Tuple<bool, IObservable<Upload>> ListIncompleteUploads(MinioClient minio, string bucketName, string prefix = null, bool recursive = true)
        {
            bool flag = false;
            IObservable<Upload> observable = null;
            try
            {
                var found = minio.BucketExistsAsync(bucketName);
                if (found.Result)
                {
                    observable = minio.ListIncompleteUploads(bucketName, prefix, recursive);
                    flag = true;
                }
                else
                {
                    throw new Exception(string.Format("存储桶[{0}]不存在", bucketName));
                }
                //IDisposable subscription = observable.Subscribe(
                //    item => Console.WriteLine($"OnNext: {item.Key}"),
                //    ex => Console.WriteLine($"OnError: {ex.Message}"),
                //    () => Console.WriteLine($"Listed the pending uploads to bucket {bucketName}"));
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }
            return Tuple.Create(flag, observable);
        }

        #endregion

        #region 存储桶策略

        /// <summary>
        /// 获取存储桶或者对象前缀的访问权限
        /// </summary>
        /// <param name="minio">连接实例</param>
        /// <param name="bucketName">存储桶名称</param>
        /// <returns></returns>
        public async static Task<Tuple<bool, string>> GetPolicy(MinioClient minio, string bucketName)
        {
            bool flag = false;
            string policyJson = string.Empty;
            try
            {
                var found = minio.BucketExistsAsync(bucketName);
                if (found.Result)
                {
                    policyJson = await minio.GetPolicyAsync(bucketName);
                    flag = true;
                }
                else
                {
                    throw new Exception(string.Format("存储桶[{0}]不存在", bucketName));
                }
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }
            return Tuple.Create(flag, policyJson);
        }

        /// <summary>
        /// 针对存储桶和对象前缀设置访问策略
        /// </summary>
        /// <param name="minio">连接实例</param>
        /// <param name="bucketName">存储桶名称</param>
        /// <returns></returns>
        public async static Task<bool> SetPolicy(MinioClient minio, string bucketName)
        {
            bool flag = false;
            try
            {
                bool found = await minio.BucketExistsAsync(bucketName);
                if (found)
                {
                    string policyJson = $@"{{""Version"":""2012-10-17"",""Statement"":[{{""Action"":[""s3:GetBucketLocation""],""Effect"":""Allow"",""Principal"":{{""AWS"":[""*""]}},""Resource"":[""arn:aws:s3:::{bucketName}""],""Sid"":""""}},{{""Action"":[""s3:ListBucket""],""Condition"":{{""StringEquals"":{{""s3:prefix"":[""foo"",""prefix/""]}}}},""Effect"":""Allow"",""Principal"":{{""AWS"":[""*""]}},""Resource"":[""arn:aws:s3:::{bucketName}""],""Sid"":""""}},{{""Action"":[""s3:GetObject""],""Effect"":""Allow"",""Principal"":{{""AWS"":[""*""]}},""Resource"":[""arn:aws:s3:::{bucketName}/foo*"",""arn:aws:s3:::{bucketName}/prefix/*""],""Sid"":""""}}]}}";

                    await minio.SetPolicyAsync(bucketName, policyJson);
                    flag = true;
                }
                else
                {
                    throw new Exception(string.Format("存储桶[{0}]不存在", bucketName));
                }
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }
            return flag;
        }

        #endregion

        #region 存储桶通知

        /// <summary>
        /// 获取存储桶的通知配置
        /// </summary>
        /// <param name="minio">连接实例</param>
        /// <param name="bucketName">存储桶名称</param>
        /// <returns></returns>
        private async static Task<Tuple<bool, string>> GetBucketNotification(MinioClient minio, string bucketName)
        {
            bool flag = false;
            string Ret = string.Empty;
            try
            {
                bool found = await minio.BucketExistsAsync(bucketName);
                if (found)
                {
                    BucketNotification notifications = await minio.GetBucketNotificationsAsync(bucketName);
                    Ret = notifications.ToXML();
                    flag = true;
                }
                else
                {
                    throw new Exception(string.Format("存储桶[{0}]不存在", bucketName));
                }
            }
            catch (MinioException e)
            {
                throw new Exception(e.Message);
            }
            return Tuple.Create(flag, Ret);
        }

        /// <summary>
        /// 给存储桶设置通知
        /// </summary>
        /// <param name="minio">连接实例</param>
        /// <param name="bucketName">存储桶名称</param>
        /// <returns></returns>
        private async static Task<bool> SetBucketNotification(MinioClient minio, string bucketName)
        {
            bool flag = false;
            try
            {
                bool found = await minio.BucketExistsAsync(bucketName);
                if (found)
                {
                    BucketNotification notification = new BucketNotification();
                    Arn topicArn = new Arn("aws", "sns", "us-west-1", "412334153608", "topicminio");

                    TopicConfig topicConfiguration = new TopicConfig(topicArn);
                    List<EventType> events = new List<EventType>() { EventType.ObjectCreatedPut, EventType.ObjectCreatedCopy };
                    topicConfiguration.AddEvents(events);
                    topicConfiguration.AddFilterPrefix("images");
                    topicConfiguration.AddFilterSuffix("jpg");
                    notification.AddTopic(topicConfiguration);

                    QueueConfig queueConfiguration = new QueueConfig("arn:aws:sqs:us-west-1:482314153608:testminioqueue1");
                    queueConfiguration.AddEvents(new List<EventType>() { EventType.ObjectCreatedCompleteMultipartUpload });
                    notification.AddQueue(queueConfiguration);

                    await minio.SetBucketNotificationsAsync(bucketName, notification);
                    flag = true;
                }
                else
                {
                    throw new Exception(string.Format("存储桶[{0}]不存在", bucketName));
                }
            }
            catch (MinioException e)
            {
                throw new Exception(e.Message);
            }
            return flag;
        }

        /// <summary>
        /// 删除存储桶上所有配置的通知
        /// </summary>
        /// <param name="minio">连接实例</param>
        /// <param name="bucketName">存储桶名称</param>
        /// <returns></returns>
        private async static Task<bool> RemoveAllBucketNotifications(MinioClient minio, string bucketName)
        {
            bool flag = false;
            try
            {
                bool found = await minio.BucketExistsAsync(bucketName);
                if (found)
                {
                    await minio.RemoveAllBucketNotificationsAsync(bucketName);
                    flag = true;
                }
                else
                {
                    throw new Exception(string.Format("存储桶[{0}]不存在", bucketName));
                }
            }
            catch (MinioException e)
            {
                throw new Exception(e.Message);
            }
            return flag;
        }

        #endregion

        #region 操作文件对象

        /// <summary>
        /// 从桶下载文件到本地
        /// </summary>
        /// <param name="minio">连接实例</param>
        /// <param name="bucketName">存储桶名称</param>
        /// <param name="objectName">存储桶里的对象名称</param>
        /// <param name="fileName">本地路径</param>
        /// <param name="sse"></param>
        /// <returns></returns>
        public async static Task<bool> FGetObject(MinioClient minio, string bucketName, string objectName, string fileName, ServerSideEncryption sse = null)
        {
            bool flag = false;
            try
            {
                bool found = await minio.BucketExistsAsync(bucketName);
                if (found)
                {
                    if (File.Exists(fileName))
                    {
                        File.Delete(fileName);
                    }
                    await minio.GetObjectAsync(bucketName, objectName, fileName, sse).ConfigureAwait(false);
                    flag = true;
                }
                else
                {
                    throw new Exception(string.Format("存储桶[{0}]不存在", bucketName));
                }
            }
            catch (MinioException e)
            {
                throw new Exception(e.Message);
            }
            return flag;
        }

        /// <summary>
        /// 上传本地文件至存储桶
        /// </summary>
        /// <param name="minio">连接实例</param>
        /// <param name="bucketName">存储桶名称</param>
        /// <param name="objectName">存储桶里的对象名称</param>
        /// <param name="fileName">本地路径</param>
        /// <returns></returns>
        public async static Task<bool> FPutObject(MinioClient minio, string bucketName, string objectName, string fileName)
        {
            bool flag = false;
            try
            {
                bool found = await minio.BucketExistsAsync(bucketName);
                if (found)
                {
                    await minio.PutObjectAsync(bucketName, objectName, fileName, contentType: "application/octet-stream");
                    flag = true;
                }
                else
                {
                    throw new Exception(string.Format("存储桶[{0}]不存在", bucketName));
                }
            }
            catch (MinioException e)
            {
                throw new Exception(e.Message);
            }
            return flag;
        }

        #endregion

        #region Presigned操作

        /// <summary>生成一个给HTTP GET请求用的presigned URL。浏览器/移动端的客户端可以用这个URL进行下载,即使其所在的存储桶是私有的。这个presigned URL可以设置一个失效时间,默认值是7天。
        /// 生成一个给HTTP GET请求用的presigned URL。浏览器/移动端的客户端可以用这个URL进行下载,即使其所在的存储桶是私有的。这个presigned URL可以设置一个失效时间,默认值是7天。
        /// </summary>
        /// <param name="minio">连接实例</param>
        /// <param name="bucketName">存储桶名称</param>
        /// <param name="objectName">存储桶里的对象名称</param>
        /// <param name="expiresInt">失效时间(以秒为单位),默认是7天,不得大于七天</param>
        /// <param name="reqParams">额外的响应头信息,支持response-expires、response-content-type、response-cache-control、response-content-disposition</param>
        /// <returns></returns>
        public async static Task<Tuple<bool, string>> PresignedGetObject(MinioClient minio, string bucketName, string objectName, int expiresInt = 1000)
        {
            bool flag = false;
            string Ret = string.Empty;
            try
            {
                bool found = await minio.BucketExistsAsync(bucketName);
                if (found)
                {
                    var reqParams = new Dictionary<string, string> { { "response-content-type", "application/json" } };
                    string presignedUrl = await minio.PresignedGetObjectAsync(bucketName, objectName, expiresInt, reqParams);
                    Ret = presignedUrl;
                    flag = true;
                }
                else
                {
                    throw new Exception(string.Format("存储桶[{0}]不存在", bucketName));
                }
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }
            return Tuple.Create(flag, Ret);
        }

        /// <summary>生成一个给HTTP PUT请求用的presigned URL。浏览器/移动端的客户端可以用这个URL进行上传,即使其所在的存储桶是私有的。这个presigned URL可以设置一个失效时间,默认值是7天。
        /// 生成一个给HTTP PUT请求用的presigned URL。浏览器/移动端的客户端可以用这个URL进行上传,即使其所在的存储桶是私有的。这个presigned URL可以设置一个失效时间,默认值是7天。
        /// </summary>
        /// <param name="minio">连接实例</param>
        /// <param name="bucketName">存储桶名称</param>
        /// <param name="objectName">存储桶里的对象名称</param>
        /// <param name="expiresInt">失效时间(以秒为单位),默认是7天,不得大于七天</param>
        /// <returns></returns>
        public async static Task<Tuple<bool, string>> PresignedPutObject(MinioClient minio, string bucketName, string objectName, int expiresInt = 1000)
        {
            bool flag = false;
            string Ret = string.Empty;
            try
            {
                bool found = await minio.BucketExistsAsync(bucketName);
                if (found)
                {
                    string presignedUrl = await minio.PresignedPutObjectAsync(bucketName, objectName, expiresInt);
                    Ret = presignedUrl;
                    flag = true;
                }
                else
                {
                    throw new Exception(string.Format("存储桶[{0}]不存在", bucketName));
                }
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }
            return Tuple.Create(flag, Ret);
        }

        /// <summary>允许给POST请求的presigned URL设置策略,比如接收对象上传的存储桶名称的策略,key名称前缀,过期策略。
        /// 允许给POST请求的presigned URL设置策略,比如接收对象上传的存储桶名称的策略,key名称前缀,过期策略。
        /// </summary>
        /// <param name="minio">连接实例</param>
        /// <param name="PostPolicy">对象的post策略</param>
        /// <returns></returns>
        public async static Task<Tuple<bool, string, Dictionary<string, string>>> PresignedPostPolicy(MinioClient minio)
        {
            bool flag = false;
            Tuple<string, Dictionary<string, string>> tdic = null;
            try
            {
                PostPolicy form = new PostPolicy();
                DateTime expiration = DateTime.UtcNow;
                form.SetExpires(expiration.AddDays(10));
                form.SetKey("my-objectname");
                form.SetBucket("my-bucketname");

                Tuple<string, Dictionary<string, string>> tuple = await minio.PresignedPostPolicyAsync(form);
                tdic = tuple;
                flag = true;
                //string curlCommand = "curl -X POST ";
                //foreach (KeyValuePair<string, string> pair in tuple.Item2)
                //{
                //    curlCommand = curlCommand + $" -F {pair.Key}={pair.Value}";
                //}
                //curlCommand = curlCommand + " -F file=@/etc/bashrc " + tuple.Item1; // https://s3.amazonaws.com/my-bucketname";
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }
            return Tuple.Create(flag, tdic.Item1, tdic.Item2);
        }

        #endregion

        #region 操作对象

        /// <summary>返回对象数据的流
        /// 返回对象数据的流
        /// </summary>
        /// <param name="minio">连接实例</param>
        /// <param name="bucketName">存储桶名称</param>
        /// <param name="objectName">存储桶里的对象名称</param>
        /// <param name="callback">处理流的回调函数</param>
        /// <returns></returns>
        public async static Task<bool> GetObjectAsync(MinioClient minio, string bucketName, string objectName, Action<Stream> callback)
        {
            bool flag = false;
            try
            {
                bool found = await minio.BucketExistsAsync(bucketName);
                if (found)
                {
                    await minio.StatObjectAsync(bucketName, objectName);
                    await minio.GetObjectAsync(bucketName, objectName, callback);
                    flag = true;
                }
                else
                {
                    throw new Exception(string.Format("存储桶[{0}]不存在", bucketName));
                }
            }
            catch (MinioException e)
            {
                throw new Exception(e.Message);
            }
            return flag;
        }

        /// <summary>下载对象指定区域的字节数组做为流。offset和length都必须传
        /// 下载对象指定区域的字节数组做为流。offset和length都必须传
        /// </summary>
        /// <param name="minio">连接实例</param>
        /// <param name="bucketName">存储桶名称</param>
        /// <param name="objectName">存储桶里的对象名称</param>
        /// <param name="offset">offset 是起始字节的位置</param>
        /// <param name="length">length是要读取的长度</param>
        /// <param name="callback">处理流的回调函数</param>
        /// <returns></returns>
        public async static Task<bool> GetObjectAsync(MinioClient minio, string bucketName, string objectName, long offset, long length, Action<Stream> callback)
        {
            bool flag = false;
            try
            {
                bool found = await minio.BucketExistsAsync(bucketName);
                if (found)
                {
                    await minio.StatObjectAsync(bucketName, objectName);
                    await minio.GetObjectAsync(bucketName, objectName, offset, length, callback);
                    flag = true;
                }
                else
                {
                    throw new Exception(string.Format("存储桶[{0}]不存在", bucketName));
                }
            }
            catch (MinioException e)
            {
                throw new Exception(e.Message);
            }
            return flag;
        }

        /// <summary>下载并将文件保存到本地文件系统
        /// 下载并将文件保存到本地文件系统
        /// </summary>
        /// <param name="minio">连接实例</param>
        /// <param name="bucketName">存储桶名称</param>
        /// <param name="objectName">存储桶里的对象名称</param>
        /// <param name="fileName">本地文件路径</param>
        /// <returns></returns>
        public async static Task<bool> GetObjectAsync(MinioClient minio, string bucketName, string objectName, string fileName)
        {
            bool flag = false;
            try
            {
                bool found = await minio.BucketExistsAsync(bucketName);
                if (found)
                {
                    if (File.Exists(fileName))
                    {
                        File.Delete(fileName);
                    }
                    await minio.StatObjectAsync(bucketName, objectName);
                    await minio.GetObjectAsync(bucketName, objectName, fileName);
                    flag = true;
                }
                else
                {
                    throw new Exception(string.Format("存储桶[{0}]不存在", bucketName));
                }
            }
            catch (MinioException e)
            {
                throw new Exception(e.Message);
            }
            return flag;
        }

        /// <summary>通过文件上传到对象中
        /// 通过文件上传到对象中
        /// </summary>
        /// <param name="minio">连接实例</param>
        /// <param name="bucketName">存储桶名称</param>
        /// <param name="objectName">存储桶里的对象名称</param>
        /// <param name="filePath">要上传的本地文件名</param>
        /// <param name="contentType">文件的Content type,默认是"application/octet-stream"</param>
        /// <param name="metaData">元数据头信息的Dictionary对象,默认是null</param>
        /// <returns></returns>
        public async static Task<bool> PutObjectAsync(MinioClient minio, string bucketName, string objectName, string filePath, string contentType = "application/octet-stream", Dictionary<string, string> metaData = null)
        {
            bool flag = false;
            try
            {
                bool found = await minio.BucketExistsAsync(bucketName);
                if (found)
                {
                    await minio.PutObjectAsync(bucketName, objectName, filePath, contentType, metaData);
                    flag = true;
                }
                else
                {
                    throw new Exception(string.Format("存储桶[{0}]不存在", bucketName));
                }
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }
            return flag;
        }

        /// <summary>通过Stream上传对象
        /// 通过Stream上传对象
        /// </summary>
        /// <param name="minio">连接实例</param>
        /// <param name="bucketName">存储桶名称</param>
        /// <param name="objectName">存储桶里的对象名称</param>
        /// <param name="data">要上传的Stream对象</param>
        /// <param name="size">流的大小</param>
        /// <param name="contentType">文件的Content type,默认是"application/octet-stream"</param>
        /// <param name="metaData">元数据头信息的Dictionary对象,默认是null</param>
        /// <returns></returns>
        public async static Task<bool> PutObjectAsync(MinioClient minio, string bucketName, string objectName, Stream data, long size, string contentType = "application/octet-stream", Dictionary<string, string> metaData = null)
        {
            bool flag = false;
            try
            {
                bool found = await minio.BucketExistsAsync(bucketName);
                if (found)
                {
                    //byte[] bs = File.ReadAllBytes(fileName);
                    //System.IO.MemoryStream filestream = new System.IO.MemoryStream(bs);

                    await minio.PutObjectAsync(bucketName, objectName, data, size, contentType, metaData);
                    flag = true;
                }
                else
                {
                    throw new Exception(string.Format("存储桶[{0}]不存在", bucketName));
                }
            }
            catch (MinioException e)
            {
                throw new Exception(e.Message);
            }
            return flag;
        }

        /// <summary>获取对象的元数据
        /// 获取对象的元数据
        /// </summary>
        /// <param name="minio">连接实例</param>
        /// <param name="bucketName">存储桶名称</param>
        /// <param name="objectName">存储桶里的对象名称</param>
        /// <returns></returns>
        public async static Task<bool> StatObject(MinioClient minio, string bucketName, string bucketObject)
        {
            bool flag = false;
            try
            {
                bool found = await minio.BucketExistsAsync(bucketName);
                if (found)
                {
                    ObjectStat statObject = await minio.StatObjectAsync(bucketName, bucketObject);
                    flag = true;
                }
                else
                {
                    throw new Exception(string.Format("存储桶[{0}]不存在", bucketName));
                }
            }
            catch (MinioException e)
            {
                throw new Exception(e.Message);
            }
            return flag;
        }

        /// <summary>从objectName指定的对象中将数据拷贝到destObjectName指定的对象
        /// 从objectName指定的对象中将数据拷贝到destObjectName指定的对象
        /// </summary>
        /// <param name="minio"></param>
        /// <param name="fromBucketName">源存储桶名称</param>
        /// <param name="fromObjectName">源存储桶中的源对象名称</param>
        /// <param name="destBucketName">目标存储桶名称</param>
        /// <param name="destObjectName">要创建的目标对象名称,如果为空,默认为源对象名称</param>
        /// <param name="copyConditions">拷贝操作的一些条件Map</param>
        /// <param name="sseSrc"></param>
        /// <param name="sseDest"></param>
        /// <returns></returns>
        public async static Task<bool> CopyObject(MinioClient minio, string fromBucketName, string fromObjectName, string destBucketName, string destObjectName, CopyConditions copyConditions = null, ServerSideEncryption sseSrc = null, ServerSideEncryption sseDest = null)
        {
            bool flag = false;
            try
            {
                bool found = await minio.BucketExistsAsync(fromBucketName);
                if (!found)
                {
                    throw new Exception(string.Format("源存储桶[{0}]不存在", fromBucketName));
                }
                bool foundtwo = await minio.BucketExistsAsync(destBucketName);
                if (!foundtwo)
                {
                    throw new Exception(string.Format("目标存储桶[{0}]不存在", destBucketName));
                }
                await minio.CopyObjectAsync(fromBucketName, fromObjectName, destBucketName, destObjectName, copyConditions, null, sseSrc, sseDest);
                flag = true;
            }
            catch (MinioException e)
            {
                throw new Exception(e.Message);
            }
            return flag;
        }

        /// <summary>删除一个对象
        /// 删除一个对象
        /// </summary>
        /// <param name="minio">连接实例</param>
        /// <param name="bucketName">存储桶名称</param>
        /// <param name="objectName">存储桶里的对象名称</param>
        /// <returns></returns>
        public async static Task<bool> RemoveObject(MinioClient minio, string bucketName, string objectName)
        {
            bool flag = false;
            try
            {
                bool found = await minio.BucketExistsAsync(bucketName);
                if (found)
                {
                    await minio.RemoveObjectAsync(bucketName, objectName);
                    flag = true;
                }
                else
                {
                    throw new Exception(string.Format("存储桶[{0}]不存在", bucketName));
                }
            }
            catch (MinioException e)
            {
                throw new Exception(e.Message);
            }
            return flag;
        }

        /// <summary>删除多个对象
        /// 删除多个对象
        /// </summary>
        /// <param name="minio">连接实例</param>
        /// <param name="bucketName">存储桶名称</param>
        /// <param name="objectsList">含有多个对象名称的IEnumerable</param>
        /// <returns></returns>
        public static async Task<bool> RemoveObjects(MinioClient minio, string bucketName, List<string> objectsList)
        {
            bool flag = false;
            try
            {
                bool found = await minio.BucketExistsAsync(bucketName);
                if (found)
                {
                    if (objectsList != null)
                    {
                        IObservable<DeleteError> objectsOservable = await minio.RemoveObjectAsync(bucketName, objectsList).ConfigureAwait(false);
                        flag = true;
                        //IDisposable objectsSubscription = objectsOservable.Subscribe(
                        //    objDeleteError => Console.WriteLine($"Object: {objDeleteError.Key}"),
                        //        ex => Console.WriteLine($"OnError: {ex}"),
                        //        () =>
                        //        {
                        //            Console.WriteLine($"Removed objects in list from {bucketName}\n");
                        //        });
                        //return;
                    }
                }
                else
                {
                    throw new Exception(string.Format("存储桶[{0}]不存在", bucketName));
                }
            }
            catch (MinioException e)
            {
                throw new Exception(e.Message);
            }
            return flag;
        }

        /// <summary>删除一个未完整上传的对象
        /// 删除一个未完整上传的对象
        /// </summary>
        /// <param name="minio">连接实例</param>
        /// <param name="bucketName">存储桶名称</param>
        /// <param name="objectName">存储桶里的对象名称</param>
        /// <returns></returns>
        public async static Task<bool> RemoveIncompleteUpload(MinioClient minio, string bucketName, string objectName)
        {
            bool flag = false;
            try
            {
                bool found = await minio.BucketExistsAsync(bucketName);
                if (found)
                {
                    await minio.RemoveIncompleteUploadAsync(bucketName, objectName);
                    flag = true;
                }
                else
                {
                    throw new Exception(string.Format("存储桶[{0}]不存在", bucketName));
                }
            }
            catch (MinioException e)
            {
                throw new Exception(e.Message);
            }
            return flag;
        }

        #endregion
    }

标签:Minio,13,minio,存储,flag,bucketName,3.1,Exception,string
From: https://blog.csdn.net/cangqiongxiaoye/article/details/139440898

相关文章

  • 【安装笔记-20240613-Linux-在 OpenWrt 的 LuCI界面支持命令行调试】
    安装笔记-系列文章目录安装笔记-20240613-Linux-在OpenWrt的LuCI界面支持命令行调试文章目录安装笔记-系列文章目录安装笔记-20240613-Linux-在OpenWrt的LuCI界面支持命令行调试前言一、软件介绍名称:ttyd主页官方介绍特点二、安装步骤测试版本:openwrt-23.05.3......
  • 【C语言】13.数据在内存中的存储
    文章目录1.整数在内存中的存储2.大小端字节序和字节序判断2.1什么是⼤⼩端?2.2为什么有⼤⼩端?2.3练习2.3.1练习12.3.2练习22.3.3练习32.3.4练习42.3.5练习52.3.6练习63.浮点数在内存中的存储3.1练习3.2浮点数的存储3.2.1浮点数存的过程3.2.2浮点数取的过......
  • 算法3.1—深度优先搜索
    P1219[USACO1.5]八皇后CheckerChallenge#includeusingnamespacestd;typedeflonglongll;intn,l[50],r[50],vis[50],a[50];intans;voiddfs(intx){if(x>n){if(ans<3)for(inti=1;i<=n;i++)cout<<a[i]<<''......
  • 香港优才优势很大!内地高考(1342 万人) 和香港高考(5 万人),你会为小孩选哪条路?
    香港身份有多香?内地高考1342万人 VS 香港DSE高考5万人如果说高考是千军万马过独木桥聪明人要选哪条桥?国内高考人数......
  • 6.13学习内容
    今天完成了计算机网络的实验三 综合性训练(搭建中小企业园区网)一、实验目的:1.通过对网络设备的连通和对拓扑的分析,加深对常见典型局域网拓扑的理解;2.通过路由建立起网络之间的连接,了解网络路由的设计与配置;3.进一步熟悉交换机、路由器的基本操作命令。二、实验设备:六个PC,两......
  • 基于Python3.11及SQL Server实现股票组合价值曲线相关计算分析
       本文中Python的版本使用的是3.11,数据库使用的是SQLSERVER2008,项目运行效果图如下:蒙特卡洛相关:突出风险最小点:夏普比率相关夏普比率无风险最大点文章中的股票每日交易数据摘取自:英为财情 https://cn.investing.com/蒙特卡洛及夏普相关计算参考【胖哥真......
  • 2024/6/13-日常练习
    第一章1.试说明数据、数据库、数据库管理系统和数据库系统的概念。答:数据是数据库中存储的基本对象数据库:是存放数据的场所。数据库管理系统:管理数据库数据及其功能的系统软件。数据库系统:由数据库、数据库管理系统、数据库管理员和数据库应用程序共同构成的系统。5.比较用......
  • 24-06-13
    是否可以继承String?String类是final类,不能被继承.继承String本身就是一个错误行为,对String类型最好的重写方式是关联关系(Has-A)和依赖关系(Use-A)而不是继承关系重载(overload)和重写(override)的区别?重载的方法能否根据返回类型进行区分?方法的重载和重写都是实现多态的方式,区别在于......
  • 6.13-栈与队列
    基础知识首先大家要知道栈和队列是STL(C++标准库)里面的两个数据结构。C++标准库是有多个版本的,要知道我们使用的STL是哪个版本,才能知道对应的栈和队列的实现原理。那么来介绍一下,三个最为普遍的STL版本:HPSTL其他版本的C++STL,一般是以HPSTL为蓝本实现出来的,HPSTL是C++S......
  • Day18 | 513. 找树左下角的值 | 112.路径总和、113.路径总和ii
    513.找树左下角的值本题递归偏难,反而迭代简单属于模板题,两种方法掌握一下题目链接/文章讲解/视频讲解:https://programmercarl.com/0513.找树左下角的值.html思考层序遍历秒了#Definitionforabinarytreenode.#classTreeNode:#def__init__(self,val=0,left......