using Minio;
using Minio.DataModel;
using Minio.Exceptions;
namespace Zowie.Common.Helper
{
/// <summary>
/// Minio
/// NuGet引用Minio.AspNetCore,版本:5.0.0
/// </summary>
public class MinioHelper
{
private MinioClient _minioClient;
public MinioHelper()
{
var apiPath = "Endpoint";//例如:192.168.1.1:9000,这里不要带http或https
var minioUser = "AccessKey";//minio账号
var minioPwd = "SecretKey";//minio密码
_minioClient = new MinioClient().WithEndpoint(apiPath).WithCredentials(minioUser, minioPwd).Build();
}
public MinioHelper(string apiPath, string minioUser, string minioPwd)
{
_minioClient = new MinioClient().WithEndpoint(apiPath).WithCredentials(minioUser, minioPwd).Build();
}
#region 操作存储桶
/// <summary>
/// 操作存储桶
/// </summary>
/// <param name="bucketName">存储桶名称</param>
/// <param name="loc">可选参数</param>
/// <returns></returns>
public async Task MakeBucket(string bucketName, string loc = "us-east-1")
{
try
{
bool found = await BucketExists(bucketName);
if (found)
{
throw new Exception(string.Format("存储桶[{0}]已存在", bucketName));
}
MakeBucketArgs args = new MakeBucketArgs()
.WithBucket(bucketName)
.WithLocation(loc);
await _minioClient.MakeBucketAsync(args);
//设置桶的访问权限(读、写、读和写)
await SetPolicyAsync(bucketName, 3);
}
catch (Exception e)
{
throw new Exception(e.Message);
}
}
/// <summary>
/// 校验是否存在,如果不存在则报错
/// </summary>
/// <param name="bucketName"></param>
private async Task CheckBucket(string bucketName)
{
bool found = await BucketExists(bucketName);
if (!found)
{
await MakeBucket(bucketName);
//throw new Exception(string.Format("存储桶[{0}]不存在", bucketName));
}
}
/// <summary>
/// 检查存储桶是否存在
/// </summary>
/// <param name="bucketName">存储桶名称</param>
/// <returns></returns>
public async Task<bool> BucketExists(string bucketName, CancellationToken cancellationToken = default(CancellationToken))
{
try
{
BucketExistsArgs args = new BucketExistsArgs()
.WithBucket(bucketName);
return await _minioClient.BucketExistsAsync(args);
}
catch (Exception e)
{
throw new Exception(e.Message);
}
}
#endregion 操作存储桶
#region 操作文件对象
/// <summary>
/// 判断桶里,对应路径文件是否存在
/// </summary>
/// <param name="bucketName">桶名</param>
/// <param name="objectName">存储桶里的对象名称,相对路径。例如/shouji/test.jpg</param>
/// <returns></returns>
public async Task<bool> FileExist(string bucketName, string objectName)
{
try
{
var obj = new StatObjectArgs().WithBucket(bucketName)
.netcore 通过Minio上传文件到存储桶中
于 2024-05-22 17:49:34 首次发布