1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370
| using Minio; using Minio.DataModel; using Minio.DataModel.Args; using Minio.DataModel.Response; using Minio.Exceptions;
namespace MinioDemo;
public sealed class MinioFileHelper { #region 字段与构造 private const int MaxExpirySeconds = 7 * 24 * 60 * 60;
private readonly IMinioClient _client;
public string DefaultBucket { get; }
public IMinioClient Client => _client;
public MinioFileHelper(string endpoint, string accessKey, string secretKey, string defaultBucket, bool? useSsl = null) : this(BuildClient(endpoint, accessKey, secretKey, useSsl), defaultBucket) { }
public MinioFileHelper(IMinioClient client, string defaultBucket) { _client = client ?? throw new ArgumentNullException(nameof(client)); if (string.IsNullOrWhiteSpace(defaultBucket)) throw new ArgumentException("默认存储桶名不能为空。", nameof(defaultBucket)); DefaultBucket = defaultBucket; }
private static IMinioClient BuildClient(string endpoint, string accessKey, string secretKey, bool? useSsl) { if (string.IsNullOrWhiteSpace(endpoint)) throw new ArgumentException("服务地址不能为空。", nameof(endpoint)); if (string.IsNullOrWhiteSpace(accessKey)) throw new ArgumentException("accessKey 不能为空。", nameof(accessKey)); if (string.IsNullOrWhiteSpace(secretKey)) throw new ArgumentException("secretKey 不能为空。", nameof(secretKey));
var host = endpoint.Trim().TrimEnd('/'); var ssl = useSsl ?? false;
return new MinioClient() .WithEndpoint(host) .WithCredentials(accessKey, secretKey) .WithSSL(ssl) .Build(); } #endregion
#region 存储桶操作 public async Task<IReadOnlyList<Bucket>> ListBucketsAsync(CancellationToken cancellationToken = default) { var result = await _client.ListBucketsAsync(cancellationToken).ConfigureAwait(false); return result.Buckets.ToList(); }
public Task<bool> BucketExistsAsync(string? bucket = null, CancellationToken cancellationToken = default) => _client.BucketExistsAsync( new BucketExistsArgs().WithBucket(ResolveBucket(bucket)), cancellationToken);
public async Task EnsureBucketAsync(string? bucket = null, CancellationToken cancellationToken = default) { var name = ResolveBucket(bucket); if (!await BucketExistsAsync(name, cancellationToken).ConfigureAwait(false)) await _client.MakeBucketAsync(new MakeBucketArgs().WithBucket(name), cancellationToken).ConfigureAwait(false); }
public Task RemoveBucketAsync(string? bucket = null, CancellationToken cancellationToken = default) => _client.RemoveBucketAsync( new RemoveBucketArgs().WithBucket(ResolveBucket(bucket)), cancellationToken); #endregion
#region 上传 public async Task<PutObjectResponse> UploadFileAsync( string localFilePath, string objectName, string? bucket = null, string? contentType = null, IProgress<Minio.DataModel.ProgressReport>? progress = null, CancellationToken cancellationToken = default) { if (string.IsNullOrWhiteSpace(localFilePath)) throw new ArgumentException("本地文件路径不能为空。", nameof(localFilePath)); if (!File.Exists(localFilePath)) throw new FileNotFoundException($"本地文件不存在: {localFilePath}", localFilePath); ValidateObjectName(objectName);
await using var stream = new FileStream(localFilePath, FileMode.Open, FileAccess.Read, FileShare.Read, 81920, useAsync: true); return await UploadStreamAsync(stream, objectName, stream.Length, contentType ?? GuessContentType(localFilePath), bucket, progress, cancellationToken) .ConfigureAwait(false); }
public async Task<PutObjectResponse> UploadStreamAsync( Stream data, string objectName, long? objectSize = null, string? contentType = null, string? bucket = null, IProgress<Minio.DataModel.ProgressReport>? progress = null, CancellationToken cancellationToken = default) { if (data is null) throw new ArgumentNullException(nameof(data)); if (!data.CanRead) throw new ArgumentException("数据流不可读。", nameof(data)); ValidateObjectName(objectName);
var size = objectSize ?? (data.CanSeek ? data.Length - data.Position : -1); if (size < 0) throw new ArgumentException("无法确定流长度,请显式传入 objectSize。", nameof(objectSize));
PutObjectArgs args = new PutObjectArgs() .WithBucket(ResolveBucket(bucket)) .WithObject(objectName) .WithStreamData(data) .WithObjectSize(size) .WithContentType(contentType ?? "application/octet-stream"); if (progress is not null) args = args.WithProgress(progress);
return await _client.PutObjectAsync(args, cancellationToken).ConfigureAwait(false); } #endregion
#region 下载 public async Task<ObjectStat> DownloadFileAsync( string objectName, string localFilePath, string? bucket = null, CancellationToken cancellationToken = default) { if (string.IsNullOrWhiteSpace(localFilePath)) throw new ArgumentException("本地文件路径不能为空。", nameof(localFilePath)); ValidateObjectName(objectName);
var fullPath = Path.GetFullPath(localFilePath); var directory = Path.GetDirectoryName(fullPath); if (!string.IsNullOrEmpty(directory)) Directory.CreateDirectory(directory);
await using var output = new FileStream(fullPath, FileMode.Create, FileAccess.Write, FileShare.None, 81920, useAsync: true); return await DownloadToStreamAsync(objectName, output, bucket, cancellationToken) .ConfigureAwait(false); }
public async Task<ObjectStat> DownloadToStreamAsync( string objectName, Stream destination, string? bucket = null, CancellationToken cancellationToken = default) { if (destination is null) throw new ArgumentNullException(nameof(destination)); if (!destination.CanWrite) throw new ArgumentException("目标流不可写。", nameof(destination)); ValidateObjectName(objectName);
Func<Stream, CancellationToken, Task> callback = async (stream, token) => await stream.CopyToAsync(destination, token).ConfigureAwait(false);
return await _client.GetObjectAsync( new GetObjectArgs() .WithBucket(ResolveBucket(bucket)) .WithObject(objectName) .WithCallbackStream(callback), cancellationToken).ConfigureAwait(false); }
public async Task<byte[]> DownloadBytesAsync( string objectName, string? bucket = null, CancellationToken cancellationToken = default) { using var buffer = new MemoryStream(); await DownloadToStreamAsync(objectName, buffer, bucket, cancellationToken).ConfigureAwait(false); return buffer.ToArray(); } #endregion
#region 查询与列举 public async Task<ObjectStat?> GetObjectInfoAsync( string objectName, string? bucket = null, CancellationToken cancellationToken = default) { ValidateObjectName(objectName); try { return await _client.StatObjectAsync( new StatObjectArgs().WithBucket(ResolveBucket(bucket)).WithObject(objectName), cancellationToken).ConfigureAwait(false); } catch (ObjectNotFoundException) { return null; } catch (BucketNotFoundException) { return null; } }
public async Task<bool> ExistsAsync( string objectName, string? bucket = null, CancellationToken cancellationToken = default) => await GetObjectInfoAsync(objectName, bucket, cancellationToken).ConfigureAwait(false) is not null;
public async Task<IReadOnlyList<Item>> ListObjectsAsync( string? prefix = null, bool recursive = true, string? bucket = null, CancellationToken cancellationToken = default) { ListObjectsArgs args = new ListObjectsArgs() .WithBucket(ResolveBucket(bucket)) .WithRecursive(recursive); if (!string.IsNullOrEmpty(prefix)) args = args.WithPrefix(prefix);
var items = new List<Item>(); await foreach (var item in _client.ListObjectsEnumAsync(args, cancellationToken)) items.Add(item); return items; } #endregion
#region 删除与复制 public Task RemoveObjectAsync( string objectName, string? bucket = null, CancellationToken cancellationToken = default) { ValidateObjectName(objectName); return _client.RemoveObjectAsync( new RemoveObjectArgs().WithBucket(ResolveBucket(bucket)).WithObject(objectName), cancellationToken); }
public async Task<IReadOnlyList<DeleteError>> RemoveObjectsAsync( IEnumerable<string> objectNames, string? bucket = null, CancellationToken cancellationToken = default) { if (objectNames is null) throw new ArgumentNullException(nameof(objectNames)); var names = objectNames.Where(name => !string.IsNullOrWhiteSpace(name)).ToList(); if (names.Count == 0) return Array.Empty<DeleteError>();
var errors = await _client.RemoveObjectsAsync( new RemoveObjectsArgs().WithBucket(ResolveBucket(bucket)).WithObjects(names), cancellationToken).ConfigureAwait(false); return errors.ToList(); }
public async Task CopyObjectAsync( string sourceObjectName, string destinationObjectName, string? sourceBucket = null, string? destinationBucket = null, CancellationToken cancellationToken = default) { ValidateObjectName(sourceObjectName); ValidateObjectName(destinationObjectName);
var tempFile = Path.Combine(Path.GetTempPath(), $"minio-copy-{Guid.NewGuid():N}.tmp"); try { var stat = await DownloadFileAsync(sourceObjectName, tempFile, sourceBucket, cancellationToken) .ConfigureAwait(false); await UploadFileAsync(tempFile, destinationObjectName, destinationBucket, string.IsNullOrWhiteSpace(stat.ContentType) ? null : stat.ContentType, cancellationToken: cancellationToken) .ConfigureAwait(false); } finally { try { if (File.Exists(tempFile)) File.Delete(tempFile); } catch (IOException) { } } } #endregion
#region 预签名 URL public Task<string> GetPresignedGetUrlAsync( string objectName, int expirySeconds = 3600, string? bucket = null) { ValidateObjectName(objectName); ValidateExpiry(expirySeconds); return _client.PresignedGetObjectAsync( new PresignedGetObjectArgs() .WithBucket(ResolveBucket(bucket)) .WithObject(objectName) .WithExpiry(expirySeconds)); }
public Task<string> GetPresignedPutUrlAsync( string objectName, int expirySeconds = 3600, string? bucket = null) { ValidateObjectName(objectName); ValidateExpiry(expirySeconds); return _client.PresignedPutObjectAsync( new PresignedPutObjectArgs() .WithBucket(ResolveBucket(bucket)) .WithObject(objectName) .WithExpiry(expirySeconds)); } #endregion
#region 内部辅助方法 private string ResolveBucket(string? bucket) => string.IsNullOrWhiteSpace(bucket) ? DefaultBucket : bucket;
private static void ValidateObjectName(string objectName) { if (string.IsNullOrWhiteSpace(objectName)) throw new ArgumentException("对象名不能为空。", nameof(objectName)); }
private static void ValidateExpiry(int expirySeconds) { if (expirySeconds < 1 || expirySeconds > MaxExpirySeconds) throw new ArgumentOutOfRangeException(nameof(expirySeconds), $"有效期须在 1 ~ {MaxExpirySeconds} 秒之间。"); }
private static string GuessContentType(string filePath) => Path.GetExtension(filePath).ToLowerInvariant() switch { ".txt" or ".log" or ".csv" => "text/plain; charset=utf-8", ".json" => "application/json; charset=utf-8", ".xml" => "application/xml; charset=utf-8", ".html" or ".htm" => "text/html; charset=utf-8", ".pdf" => "application/pdf", ".png" => "image/png", ".jpg" or ".jpeg" => "image/jpeg", ".gif" => "image/gif", ".zip" => "application/zip", ".mp4" => "video/mp4", _ => "application/octet-stream" }; #endregion }
|