LFlow/LFlow.Base/Utils/MinioService.cs

172 lines
6.3 KiB
C#

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 = "testbucket";
public MinIOService(IMinioClient _minioClient)
{
minioClient = _minioClient;
bucketManager = new BucketManager(_minioClient);
}
public async Task<string> 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)
.WithStreamData(file.OpenReadStream())
.WithObjectSize(file.Length)
.WithContentType(file.ContentType);
var response = await minioClient.PutObjectAsync(putObjectArgs);
Console.WriteLine($"文件 '{fileName}' 上传到 bucket '{bucketName}' 中,文件名为 '{objectName}'。");
return objectName;
}
catch (Exception ex)
{
// 处理异常
throw new ApplicationException("文件上传失败", ex);
}
}
/// <summary>
/// 获取桶列表
/// </summary>
/// <returns></returns>
public async Task<List<string>> GetBuckets()
{
var list = await minioClient.ListBucketsAsync().ConfigureAwait(false);
var buckets = list.Buckets.Select(b => b.Name).ToList();
return buckets;
}
/// <summary>
/// 下载接口
/// </summary>
/// <returns></returns>
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);
}
}
/// <summary>
/// 后缀名枚举
/// </summary>
/// <param name="fileExtension"></param>
/// <returns></returns>
//public string DetermineFileType(string fileExtension)
//{
// HashSet<string> supportedImageExtensions = new HashSet<string>
// {
// ".jpg",".jpeg", ".png",".gif",".bmp",".tiff",".tif",".svg",".webp", ".ico"
// };
// HashSet<string> supportedVideoExtensions = new HashSet<string>
// {
// ".mp4",".avi",".mkv",".mov",".wmv",".flv",".webm"
// };
// HashSet<string> supportedDocumentExtensions = new HashSet<string>
// {
// ".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();
// }
}
}