using MasstransferCommon.Model.Entity;
using MasstransferInfrastructure.Database.Sqlite;
using Minio;
using Minio.DataModel.Args;
namespace MasstransferCommunicate.Minio;
///
/// Minio工具类
///
public class MinioHelper
{
private readonly IMinioClient _client;
private static MinioHelper? _instance;
private static readonly object Lock = new();
private static SqliteHelper _sqliteHelper = SqliteHelper.GetInstance();
private MinioHelper(string endpoint, string accessKey, string secretKey)
{
_client = new MinioClient()
.WithSSL()
.WithEndpoint(endpoint)
.WithCredentials(accessKey, secretKey)
.Build();
}
public static MinioHelper GetInstance()
{
lock (Lock)
{
var minio = _sqliteHelper.Query("select * from minio_params limit 1").FirstOrDefault();
_instance ??= new MinioHelper(minio.MinioEndpoint, minio.MinioAccessKey, minio.MinioSecretKey);
return _instance;
}
}
///
/// 判断bucket 是否存在
///
///
///
public async Task BucketExistsAsync(string bucketName)
{
return await _client.BucketExistsAsync(new BucketExistsArgs().WithBucket(bucketName));
}
///
/// 上传文件
///
///
///
///
///
public async Task UploadFileAsync(string bucketName, string fileName, string filePath)
{
try
{
if (!await BucketExistsAsync(bucketName))
{
await _client.MakeBucketAsync(new MakeBucketArgs().WithBucket(bucketName));
}
await _client.PutObjectAsync(new PutObjectArgs()
.WithBucket(bucketName)
.WithObject(fileName)
.WithFileName(filePath));
Console.WriteLine("文件上传成功");
return $"{bucketName}/{fileName}";
}
catch (Exception e)
{
Console.WriteLine($"文件上传失败: {e}");
return "";
}
}
///
/// 下载文件
///
///
///
///
public async Task DownloadFileAsync(string bucketName, string fileName, string filePath)
{
if (!await BucketExistsAsync(bucketName))
{
await _client.MakeBucketAsync(new MakeBucketArgs().WithBucket(bucketName));
}
await _client.GetObjectAsync(new GetObjectArgs()
.WithBucket(bucketName)
.WithObject(fileName)
.WithFile(filePath));
}
///
/// 删除文件
///
///
///
public async Task DeleteFileAsync(string bucketName, string fileName)
{
if (!await BucketExistsAsync(bucketName))
{
await _client.MakeBucketAsync(new MakeBucketArgs().WithBucket(bucketName));
}
await _client.RemoveObjectAsync(new RemoveObjectArgs()
.WithBucket(bucketName)
.WithObject(fileName));
}
}