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");


    }
}
相关推荐
就是有点傻1 小时前
C#中面试的常见问题007
面试·c#·wpf
周杰伦fans2 小时前
Java与C#
java·开发语言·c#
三天不学习3 小时前
C#.Net筑基-类型系统
c#·.net
csdn_aspnet4 小时前
C# 程序来计算三角形的面积(Program to find area of a triangle)
算法·c#
xcLeigh5 小时前
C# Winform贪吃蛇小游戏源码
开发语言·c#
.NET快速开发框架6 小时前
一文搞懂flex(弹性盒布局)
c#·.netcore·web前端·开发技术·rdif·rdiframework.net
呆呆小雅6 小时前
C# 结构体
android·java·c#
生财6 小时前
获取字 short WORD 上指定的位是否有效
java·服务器·c#
呆呆小雅6 小时前
C# 封装
java·开发语言·c#
就是有点傻7 小时前
C#中面试的常见问题006
开发语言·面试·c#·wpf