using System;
using System.IO;
using System.Threading.Tasks;
using Minio;
using Minio.DataModel;
using Minio.DataModel.Args;
namespace Hopetry.Services
{
public static class UploadHelper
{
///
/// 带重试机制的安全文件上传
///
/// MinIO客户端
/// 存储桶名称
/// 本地文件路径
/// 对象名称
/// 进度回调
/// 上传是否成功
public static async Task SafeUploadFileAsync(
IMinioClient client,
string bucketName,
string filePath,
string objectName,
IProgress progressCallback = null)
{
// 验证输入参数
if (string.IsNullOrWhiteSpace(bucketName) || string.IsNullOrWhiteSpace(filePath) || string.IsNullOrWhiteSpace(objectName))
{
Console.WriteLine("上传参数验证失败");
return false;
}
// 检查文件是否存在
if (!File.Exists(filePath))
{
Console.WriteLine($"文件不存在: {filePath}");
return false;
}
try
{
var putObjectArgs = new PutObjectArgs()
.WithBucket(bucketName)
.WithObject(objectName)
.WithFileName(filePath)
.WithProgress(progressCallback);
await client.PutObjectAsync(putObjectArgs);
return true; // 上传成功
}
catch (Exception ex)
{
Console.WriteLine($"上传失败: {ex.Message}");
return false; // 让调用方决定是否重试
}
}
///
/// 检查文件是否已存在于MinIO中
///
/// MinIO客户端
/// 存储桶名称
/// 对象名称
/// 文件是否存在
public static async Task CheckFileExistsAsync(IMinioClient client, string bucketName, string objectName)
{
try
{
var args = new StatObjectArgs()
.WithBucket(bucketName)
.WithObject(objectName);
var stat = await client.StatObjectAsync(args);
return true;
}
catch (Exception)
{
// 文件不存在或无法访问
return false;
}
}
}
}