MasstransferExporter/MasstransferInfrastructure/Minio/MinioHelper.cs

88 lines
2.5 KiB
C#

using Minio;
using Minio.DataModel.Args;
namespace MasstransferCommunicate.Minio;
/// <summary>
/// Minio工具类
/// </summary>
public class MinioHelper
{
private readonly IMinioClient _client;
public MinioHelper(string endpoint, string accessKey, string secretKey)
{
_client = new MinioClient()
.WithEndpoint(endpoint)
.WithCredentials(accessKey, secretKey)
.Build();
}
/// <summary>
/// 判断bucket 是否存在
/// </summary>
/// <param name="bucketName"></param>
/// <returns></returns>
public async Task<bool> BucketExistsAsync(string bucketName)
{
return await _client.BucketExistsAsync(new BucketExistsArgs().WithBucket(bucketName));
}
/// <summary>
/// 上传文件
/// </summary>
/// <param name="bucketName"></param>
/// <param name="fileName"></param>
/// <param name="filePath"></param>
/// <returns></returns>
public async Task<string> UploadFileAsync(string bucketName, string fileName, string filePath)
{
if (!await BucketExistsAsync(bucketName))
{
await _client.MakeBucketAsync(new MakeBucketArgs().WithBucket(bucketName));
}
await _client.PutObjectAsync(new PutObjectArgs()
.WithBucket(bucketName)
.WithObject(fileName)
.WithFileName(filePath));
return $"{bucketName}/{fileName}";
}
/// <summary>
/// 下载文件
/// </summary>
/// <param name="bucketName"></param>
/// <param name="fileName"></param>
/// <param name="filePath"></param>
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));
}
/// <summary>
/// 删除文件
/// </summary>
/// <param name="bucketName"></param>
/// <param name="fileName"></param>
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));
}
}