c#使用Minio(3.1.13版本)

增加minio配置

appsetting中

cs 复制代码
    "MinioUrl": "MinioClientUrl",
    "MinioUser": "UserName",
    "MinioPassword": "Password",
    "MinioBucketName": "bucketName",

Stratup

cs 复制代码
 public Startup(IConfiguration configuration)
 {
     
     Configuration = configuration;
     MinioUrl = Configuration.GetConnectionString("MinioUrl");
     MinioUser = Configuration.GetConnectionString("MinioUser");
     MinioPassword = Configuration.GetConnectionString("MinioPassword");
     MinioBucketName = Configuration.GetConnectionString("MinioBucketName");
 }

定义minio服务类

新建MinioClient类

cs 复制代码
using Microsoft.AspNetCore.Http;
using Minio;
using ServiceReference;
using System;
using System.IO;
using System.Threading.Tasks;


namespace GreeEquipmentConSysAPI.Commons
{
    public class MinioServer
    {
        /// <summary>
        /// 定义MinIO客户端对象
        /// </summary>
        private MinioClient minio;

        /// <summary>
        /// 构造函数中注入实例
        /// </summary>
        public MinioServer()
        {
            minio = new MinioClient(Startup.MinioUrl, Startup.MinioUser, Startup.MinioPassword);
        }

        /// <summary>
        /// 上传文件到MinIO
        /// </summary>
        public async Task<string> UploadFile(Stream stream, string bucketName, string objectName, string path)
        {
            return await Task.Run(async () =>
            {
                var retMsg = string.Empty;
                try
                {
                    //检查是否存在桶
                    bool existBucket = await minio.BucketExistsAsync(bucketName);
                    if (!existBucket)
                    {
                        //创建桶
                        await minio.MakeBucketAsync(bucketName);

                        //设置桶的访问权限(读、写、读和写)
                        await SetPolicyAsync(bucketName, 3);
                    }

                    //检查设备令牌是否重复
                    //List<string> listfile = getPreMinioObjectNameList(edgeName + "/" + acesst);

                    //if (listfile.Count == 0)
                    //{
                    //上传文件到桶中
                    await minio.PutObjectAsync(bucketName, "/" + path + "/" + objectName, stream, stream.Length);
                    retMsg = "success";
                    //}
                    //else
                    //{
                    //    retMsg = "设备令牌重复";
                    //}
                }
                catch (Exception e)
                {
                    retMsg = "文件上传错误:" + e.Message;
                }
                return retMsg;
            });
        }

        /// <summary>
        /// 从minio删除文件
        /// </summary>
        /// <returns></returns>
        public async Task<string> RemoveFile(string bucketName, string objectName)
        {
            return await Task.Run(async () =>
            {
                var retMsg = string.Empty;
                try
                {
                    //检查是否存在桶
                    bool existBucket = await minio.BucketExistsAsync(bucketName);
                    if (!existBucket)
                    {
                       return "minio桶不存在!";
                    }
                    await minio.RemoveObjectAsync(bucketName, objectName);
                    retMsg = "success";
                }
                catch (Exception e)
                {
                    retMsg = "文件删除错误:" + e.Message;
                }
                return retMsg;
            });
        }

        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="bucketName">minio桶名称</param>
        /// <param name="objectName">存储对象名称</param>
        /// <returns></returns>
        public async Task<dynamic> downLoadFile(string bucketName, string objectName)
        {
            var memoryStream = new MemoryStream();
            try
            {     
                await minio.GetObjectAsync(bucketName, objectName, (stream) => { stream.CopyTo(memoryStream); });
                memoryStream.Position = 0;
            }
            catch (Exception e)
            {
                return "未找到文件,下载失败" + e.Message;
            }
            return memoryStream;
        }

        /// <summary>
        /// 检查minio桶是否存在
        /// </summary>
        /// <param name="bucketName">存储桶名称</param>
        /// <returns></returns>
        public async Task<bool> BucketExistsAsync(string bucketName)
        {
            bool existBucket = await minio.BucketExistsAsync(bucketName);
            return existBucket;
        }

        /// <summary>
        /// 设置桶的访问策略(读、写、读和写)
        /// </summary>
        /// <param name="bucketName"></param>
        /// <param name="policyType"></param>
        /// <returns></returns>
        private async Task SetPolicyAsync(string bucketName, int policyType = 1)
        {
            //设置桶的访问权限(读、写、读和写)
            var policyRead = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":{\"AWS\":[\"*\"]},\"Action\":[\"s3:GetBucketLocation\"],\"Resource\":[\"arn:aws:s3:::BUCKETNAME\"]},{\"Effect\":\"Allow\",\"Principal\":{\"AWS\":[\"*\"]},\"Action\":[\"s3:ListBucket\"],\"Resource\":[\"arn:aws:s3:::BUCKETNAME\"],\"Condition\":{\"StringEquals\":{\"s3:prefix\":[\"BUCKETPREFIX\"]}}},{\"Effect\":\"Allow\",\"Principal\":{\"AWS\":[\"*\"]},\"Action\":[\"s3:GetObject\"],\"Resource\":[\"arn:aws:s3:::BUCKETNAME/BUCKETPREFIX*\"]}]}";
            var policyWrite = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":{\"AWS\":[\"*\"]},\"Action\":[\"s3:GetBucketLocation\",\"s3:ListBucketMultipartUploads\"],\"Resource\":[\"arn:aws:s3:::BUCKETNAME\"]},{\"Effect\":\"Allow\",\"Principal\":{\"AWS\":[\"*\"]},\"Action\":[\"s3:AbortMultipartUpload\",\"s3:DeleteObject\",\"s3:ListMultipartUploadParts\",\"s3:PutObject\"],\"Resource\":[\"arn:aws:s3:::BUCKETNAME/BUCKETPREFIX*\"]}]}";
            var policyReadWrite = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":{\"AWS\":[\"*\"]},\"Action\":[\"s3:GetBucketLocation\",\"s3:ListBucketMultipartUploads\"],\"Resource\":[\"arn:aws:s3:::BUCKETNAME\"]},{\"Effect\":\"Allow\",\"Principal\":{\"AWS\":[\"*\"]},\"Action\":[\"s3:ListBucket\"],\"Resource\":[\"arn:aws:s3:::BUCKETNAME\"],\"Condition\":{\"StringEquals\":{\"s3:prefix\":[\"BUCKETPREFIX\"]}}},{\"Effect\":\"Allow\",\"Principal\":{\"AWS\":[\"*\"]},\"Action\":[\"s3:PutObject\",\"s3:AbortMultipartUpload\",\"s3:DeleteObject\",\"s3:GetObject\",\"s3:ListMultipartUploadParts\"],\"Resource\":[\"arn:aws:s3:::BUCKETNAME/BUCKETPREFIX*\"]}]}";

            var policySet = policyType == 1 ? policyRead :
               policyType == 2 ? policyWrite : policyReadWrite;

            await minio.SetPolicyAsync(bucketName, policySet.Replace("BUCKETNAME", bucketName).Replace("BUCKETPREFIX", "*.*"));
        }

    }
}

使用

cs 复制代码
public class MachineDataController:ControllerBase
{
    /// <summary>
    /// 定义MinIO客户端对象
    /// </summary>
    private MinioServer minioServer = new MinioServer();

    /// <summary>
    /// 构造函数中注入实例
    /// </summary>
    public MachineDataController()
    {

        minio = new MinioClient(Startup.MinioUrl, Startup.MinioUser, Startup.MinioPassword);
    }

    public void function() {
        string res = string.Empty;
        //上传文件
        res = minioServer.UploadFile(pdfFile[0].OpenReadStream(), "greebaseapprovalpdfs", departName + "_" + year + "_" + month + ".pdf", departName).Result;
        //下载文件
        var memoryStream = new MemoryStream();
        memoryStream = await minioServer.downLoadFile("greebaseapprovalpdfs", "/" + departName + "/" + fileName);
        return File(memoryStream, "application/pdf");
        //删除文件
         string resMsg = minioServer.RemoveFile("greebaseapprovalpdfs", "/" + departName + "/" + departName + "_" + year + "_" + month + ".pdf").Result;
        // 检查桶是否存在
         bool existBucket = await minioServer.BucketExistsAsync("greebaseapprovalpdfs");


    }
}
相关推荐
测试界的酸菜鱼40 分钟前
C# NUnit 框架:高效使用指南
开发语言·c#·log4j
小码编匠1 小时前
领域驱动设计(DDD)要点及C#示例
后端·c#·领域驱动设计
工业甲酰苯胺1 小时前
C# 单例模式的多种实现
javascript·单例模式·c#
yi碗汤园1 小时前
【一文了解】C#基础-集合
开发语言·前端·unity·c#
Humbunklung3 小时前
一种EF(EntityFramework) MySQL修改表名去掉dbo前缀的方法
数据库·mysql·c#
小码编匠13 小时前
一款 C# 编写的神经网络计算图框架
后端·神经网络·c#
Envyᥫᩣ16 小时前
C#语言:从入门到精通
开发语言·c#
IT技术分享社区1 天前
C#实战:使用腾讯云识别服务轻松提取火车票信息
开发语言·c#·云计算·腾讯云·共识算法
△曉風殘月〆1 天前
WPF MVVM入门系列教程(二、依赖属性)
c#·wpf·mvvm