From 52be00103c75ba7de2e987ed7b581f6b302bdfb0 Mon Sep 17 00:00:00 2001 From: "SINVO\\yangshunli" Date: Mon, 4 Nov 2024 15:11:14 +0800 Subject: [PATCH] =?UTF-8?q?105067=20MinIO=E8=B0=83=E8=AF=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- LFlow.Base/Base.xml | 39 ++++ LFlow.Base/LFlow.Base.csproj | 1 + LFlow.Base/Program.cs | 20 ++- LFlow.Base/Utils/BucketManager.cs | 138 ++++++++++++++ LFlow.Base/Utils/MinioService.cs | 168 ++++++++++++++++++ LFlow.Base/appsettings.json | 44 +++-- .../Controller/VersionManagementController.cs | 23 ++- 7 files changed, 412 insertions(+), 21 deletions(-) create mode 100644 LFlow.Base/Utils/BucketManager.cs create mode 100644 LFlow.Base/Utils/MinioService.cs diff --git a/LFlow.Base/Base.xml b/LFlow.Base/Base.xml index 96e4fc5..28e9a03 100644 --- a/LFlow.Base/Base.xml +++ b/LFlow.Base/Base.xml @@ -323,6 +323,33 @@ + + + 1、判断bucket是否存在 + + + + + + + 2、创建一个bucket + + + + + + + 3、移除一个bucket + + + + + + + 4、获取已有的bucket列表 + + + CodeFirst @@ -370,6 +397,18 @@ + + + 获取桶列表 + + + + + + 下载接口 + + + 对象转换为where条件 diff --git a/LFlow.Base/LFlow.Base.csproj b/LFlow.Base/LFlow.Base.csproj index 0fd003d..4fc8934 100644 --- a/LFlow.Base/LFlow.Base.csproj +++ b/LFlow.Base/LFlow.Base.csproj @@ -15,6 +15,7 @@ + diff --git a/LFlow.Base/Program.cs b/LFlow.Base/Program.cs index 39b1225..24165f7 100644 --- a/LFlow.Base/Program.cs +++ b/LFlow.Base/Program.cs @@ -2,13 +2,17 @@ using LFlow.Base.Utils; using LFlow.Cache; using LFlow.InternalEventBus; - +using Minio; using LFlow.Middleware; using LFlow.Middleware.Register; using Serilog; using Serilog.Events; using SqlSugar; using System.Reflection; +using Microsoft.AspNetCore.DataProtection; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Options; +using Microsoft.OpenApi.Models; namespace LFlow.Base; /// @@ -63,6 +67,19 @@ public static class Program { c.Conventions.Add(new ApiExplorerGroupPerVersionConvention()); }); + string endPoint = "172.30.20.40:9000"; + string accessKey = "name"; + string secretKey = "password"; + bool secure = true; + builder.Services.AddSingleton + (s => + new MinioClient() + .WithEndpoint(endPoint) + .WithCredentials(accessKey, secretKey) + .WithSSL(secure) + .Build() + ); + builder.Services.AddSwaggerGen(u => { @@ -180,6 +197,7 @@ public static class Program app.Run(); } + /// /// 配置SqlSugar /// diff --git a/LFlow.Base/Utils/BucketManager.cs b/LFlow.Base/Utils/BucketManager.cs new file mode 100644 index 0000000..4acdf5d --- /dev/null +++ b/LFlow.Base/Utils/BucketManager.cs @@ -0,0 +1,138 @@ +using Minio.DataModel.Args; +using Minio.DataModel.Result; +using Minio.Exceptions; +using Minio; +using Minio.DataModel.Args; +using Minio.Exceptions; +using Minio; +using Minio.DataModel.Result; + + +namespace LFlow.Base.Utils +{ + public class BucketManager + { + public static IMinioClient minioClient; + + public BucketManager(IMinioClient IminioClient) { + + minioClient= IminioClient; + } + /// + /// 1、判断bucket是否存在 + /// + /// + /// + public static async Task IsExistStr(string bucketName) + { + + try + { + BucketExistsArgs args = new BucketExistsArgs().WithBucket(bucketName); + + bool found = await minioClient.BucketExistsAsync(args).ConfigureAwait(false); + + Console.WriteLine("found。。。。。。", found); + + if (found) + { + Console.WriteLine($"{bucketName}桶已存在"); + return $"{bucketName}桶已存在"; + } + else + { + Console.WriteLine($"{bucketName}桶不存在"); + return $"{bucketName}桶不存在"; + } + } + catch (MinioException e) + { + Console.WriteLine("[Bucket] Exception: {0}", e); + return "出错啦!!!"; + } + } + + /// + /// 2、创建一个bucket + /// + /// + /// + public static async Task Create(string? bucketName) + { + try + { + BucketExistsArgs args = new BucketExistsArgs().WithBucket(bucketName); + + bool found = await minioClient.BucketExistsAsync(args).ConfigureAwait(false); + + if (found) + { + return $"{bucketName}桶已存在"; + } + else + { + MakeBucketArgs makeBucketArgs = new MakeBucketArgs().WithBucket(bucketName); + await minioClient.MakeBucketAsync(makeBucketArgs).ConfigureAwait(false); + + return $"{bucketName}桶已成功创建"; + } + } + catch (MinioException e) + { + Console.WriteLine("[Bucket] Exception: {0}", e); + return "出错啦!!!"; + } + } + + /// + /// 3、移除一个bucket + /// + /// + /// + public static async Task Delete(string? bucketName) + { + try + { + BucketExistsArgs args = new BucketExistsArgs().WithBucket(bucketName); + + bool found = await minioClient.BucketExistsAsync(args).ConfigureAwait(false); + + if (!found) + { + return $"{bucketName}桶不存在"; + } + else + { + RemoveBucketArgs removeBucketArgs = new RemoveBucketArgs().WithBucket(bucketName); + + await minioClient.RemoveBucketAsync(removeBucketArgs); + + return $"{bucketName}桶删除成功"; + } + } + catch (MinioException e) + { + Console.WriteLine("[Bucket] Exception: {0}", e); + return "出错啦!!!"; + } + } + + /// + /// 4、获取已有的bucket列表 + /// + /// + public static async Task GetList() + { + try + { + return await minioClient.ListBucketsAsync(); + } + catch (MinioException e) + { + Console.WriteLine("Error occurred: " + e); + return null; + } + } + + } +} diff --git a/LFlow.Base/Utils/MinioService.cs b/LFlow.Base/Utils/MinioService.cs new file mode 100644 index 0000000..acb9bd3 --- /dev/null +++ b/LFlow.Base/Utils/MinioService.cs @@ -0,0 +1,168 @@ +using Microsoft.VisualBasic.FileIO; +using Minio; +using Minio.DataModel; +using Minio.DataModel.Args; +using Minio.Exceptions; +using System; +using System.Threading.Tasks; +using static System.Runtime.InteropServices.JavaScript.JSType; + +namespace LFlow.Base.Utils +{ + public class MinIOService + { + private readonly IMinioClient minioClient; + private readonly BucketManager bucketManager; + private static string bucketName = "kecheng"; + + public MinIOService(IMinioClient _minioClient) + { + minioClient = _minioClient; + bucketManager = new BucketManager(_minioClient); + } + + + public async Task Upload(IFormFile file) + { + try + { + + //logger.LogInformation("文件开始上传"); + string uploadsPath = Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "uploads"); + if (!Directory.Exists(uploadsPath)) + { + Directory.CreateDirectory(uploadsPath); + } + string fileName = file.FileName; + string filePath = Path.Combine(uploadsPath, fileName); + string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fileName); + string fileExtension = Path.GetExtension(fileName); + string newFileName = null; + int counter = 1; + while (File.Exists(filePath)) + { + //重新命名文件 + string Name = $"{fileNameWithoutExtension}_{counter}{fileExtension}"; + filePath = Path.Combine(uploadsPath, Name); + newFileName = Path.GetFileNameWithoutExtension(filePath); + counter++; + } + if (newFileName == null) + { + newFileName = Path.GetFileNameWithoutExtension(fileName); + } + using (var stream = new FileStream(filePath, FileMode.Create)) + { + file.CopyTo(stream); + } + + //AddFileInfo(filePath, Path.GetFileNameWithoutExtension(fileName), newFileName); + var beArgs = new BucketExistsArgs() + .WithBucket(bucketName); + + bool found = await minioClient.BucketExistsAsync(beArgs); + if (!found) + { + var mbArgs = new MakeBucketArgs() + .WithBucket(bucketName); + await minioClient.MakeBucketAsync(mbArgs).ConfigureAwait(false); + } + // 设置上传文件的对象名 + var objectName = Guid.NewGuid().ToString() + Path.GetExtension(file.FileName); + var putObjectArgs = new PutObjectArgs() + .WithBucket(bucketName) + .WithObject(objectName) + .WithFileName(filePath) + .WithContentType(file.ContentType); + await minioClient.PutObjectAsync(putObjectArgs).ConfigureAwait(false); + Console.WriteLine($"文件 '{filePath}' 上传到 bucket '{bucketName}' 中,文件名为 '{objectName}'。"); + return objectName; + } + catch (Exception ex) + { + // 处理异常 + throw new ApplicationException("文件上传失败", ex); + } + } + + /// + /// 获取桶列表 + /// + /// + public async Task> GetBuckets() + { + var list = await minioClient.ListBucketsAsync().ConfigureAwait(false); + var buckets = list.Buckets.Select(b => b.Name).ToList(); + return buckets; + } + + + + + + + /// + /// 下载接口 + /// + /// + public async Task DownLoad() + { + try + { + StatObjectArgs statObjectArgs = new StatObjectArgs() + .WithBucket(bucketName) + .WithObject("替换你上传到minio服务器中生成的objectName"); + await minioClient.StatObjectAsync(statObjectArgs); + + GetObjectArgs getObjectArgs = new GetObjectArgs() + .WithBucket(bucketName) + .WithObject("替换你上传到minio服务器中生成的objectName") + .WithFile("D:\\photo.jpg"); //替换你实际的文件输出路径 + await minioClient.GetObjectAsync(getObjectArgs); + } + catch (MinioException e) + { + Console.Out.WriteLine("Error occurred:" + e); + } + } + + /// + /// 后缀名枚举 + /// + /// + /// + //public string DetermineFileType(string fileExtension) + //{ + // HashSet supportedImageExtensions = new HashSet + // { + // ".jpg",".jpeg", ".png",".gif",".bmp",".tiff",".tif",".svg",".webp", ".ico" + // }; + + // HashSet supportedVideoExtensions = new HashSet + // { + // ".mp4",".avi",".mkv",".mov",".wmv",".flv",".webm" + // }; + + // HashSet supportedDocumentExtensions = new HashSet + // { + // ".doc",".docx",".pdf",".txt",".ppt",".pptx",".xls",".xlsx", + // }; + // if (supportedDocumentExtensions.Contains(fileExtension.ToLower())) + // { + // return FileType.document.ToString(); + // } + // else if (supportedImageExtensions.Contains(fileExtension.ToLower())) + // { + // return FileType.image.ToString(); + // } + // else if (supportedVideoExtensions.Contains(fileExtension.ToLower())) + // { + // return FileType.video.ToString(); + // } + // else + // { + // return FileType.other.ToString(); + // } + } +} + diff --git a/LFlow.Base/appsettings.json b/LFlow.Base/appsettings.json index b146ec7..a06a403 100644 --- a/LFlow.Base/appsettings.json +++ b/LFlow.Base/appsettings.json @@ -1,22 +1,28 @@ { - "Urls": "https://127.0.0.1:8443;http://127.0.0.1:8088", - "Serilog": { - "MinimumLevel": { - "Default": "Debug", - "Override": { - "Microsoft.AspNetCore.Mvc": "Debug", - "Microsoft.AspNetCore.Routing": "Debug", - "Microsoft.AspNetCore.Hosting": "Debug" - } + "Urls": "https://172.30.20.40:3452;http://172.30.20.40:3453", + "Serilog": { + "MinimumLevel": { + "Default": "Debug", + "Override": { + "Microsoft.AspNetCore.Mvc": "Debug", + "Microsoft.AspNetCore.Routing": "Debug", + "Microsoft.AspNetCore.Hosting": "Debug" + } + }, + "WriteTo": [ + { + "Name": "Console" + } + ] }, - "WriteTo": [ - { - "Name": "Console" - } - ] - }, - "AllowedHosts": "*", - "ConnectionStrings": { - "DefaultConnection": "Data Source=192.168.3.85;Initial Catalog=PluginAdmin-dev;User Id=sa;Password=Sa1234;Encrypt=True;TrustServerCertificate=True" - } + "MinIoConfig": { + "EndPoint": "localhost:9000", + "AccessKey": "name", + "SecretKey": "passsword", + "UseSSL": false + }, + "AllowedHosts": "*", + "ConnectionStrings": { + "DefaultConnection": "Data Source=192.168.3.85;Initial Catalog=PluginAdmin-dev;User Id=sa;Password=Sa1234;Encrypt=True;TrustServerCertificate=True" + } } \ No newline at end of file diff --git a/LFlow.VersionManagement/Controller/VersionManagementController.cs b/LFlow.VersionManagement/Controller/VersionManagementController.cs index f8bceb4..0dbaae9 100644 --- a/LFlow.VersionManagement/Controller/VersionManagementController.cs +++ b/LFlow.VersionManagement/Controller/VersionManagementController.cs @@ -4,11 +4,17 @@ using LFlow.VersionManagement.Enums; using LFlow.VersionManagement.Model; using LFlow.VersionManagement.Service; using Mapster; +using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; +using Minio; +using SqlSugar; namespace LFlow.VersionManagement.Controller; -public class VersionManagementController(IVersionManagementService service) : BaseController +public class VersionManagementController(IVersionManagementService service, IMinioClient _client) : BaseController { + + + [HttpDelete] public int DeleteById(string id) { @@ -55,6 +61,21 @@ public class VersionManagementController(IVersionManagementService service) : Ba var result = service.Save(entity, isUpdate).Adapt(); return ApiResult.SuccessResult(result); } + /// + /// 保存文件 + /// + /// + /// + /// + [HttpPost] + public async Task SaveFile(IFormFile formFile, bool isUpdate) + { + + MinIOService minIOService = new MinIOService(_client); + var guid= minIOService.Upload(formFile); + + return (IResult)Ok(guid.Result); + } [HttpPost] public List Search(VersionDto whereObj)