MinIO在.NET项目中的集成

使用MinIO可以非常方便地构建文件服务系统,本文记录MinIO的基本使用方法,非常简答。

启动MinIO服务

通过容器部署是最好的方式。9000是API服务的端口号,9001是管理台的端口号。

1
2
3
4
5
6
7
8
9
10
11
12
13
# 1. 创建数据持久目录
mkdir -p /data/minio

# 2. 启动容器
docker run -d \
-p 9000:9000 \
-p 9001:9001 \
--name minio \
--restart=always \
-v /data/minio:/data \
-e "MINIO_ROOT_USER=admin" \
-e "MINIO_ROOT_PASSWORD=12345678" \
quay.io/minio/minio server /data --console-address ":9001"

以下是对应的Compose文件,启动和终止服务更加方便:docker compose -f docker-compose-minio.yml up -d。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
services:
minio:
image: quay.io/minio/minio
container_name: minio
restart: always
ports:
- "9000:9000"
- "9001:9001"
environment:
MINIO_ROOT_USER: admin
MINIO_ROOT_PASSWORD: 12345678
volumes:
- /data/minio:/data
command: server /data --console-address ":9001"

管理员创建密钥和数据桶

密钥包括两个:Access Key和Secret Key,后端与MinIO建立连接时需要这两个密钥。

创建密钥

可以事先在管理台创建好数据桶,也可以通过API自动创建,最好手动创建并配置好数据桶的权限。

创建数据桶

管理员相关信息:

1
2
3
4
Endpoint:http://xxx:xxx
AK:xxx
SK:xxx
BucketName:bucket01

与后端项目集成

MinIO工具类

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 字段与构造
/// <summary>预签名 URL 允许的最大有效期(秒),MinIO 限制为 7 天。</summary>
private const int MaxExpirySeconds = 7 * 24 * 60 * 60;

private readonly IMinioClient _client;

/// <summary>默认存储桶名。</summary>
public string DefaultBucket { get; }

/// <summary>底层客户端,便于调用本类未封装的高级 API。</summary>
public IMinioClient Client => _client;

/// <summary>
/// 创建工具类。
/// </summary>
/// <param name="endpoint">服务地址, host:port</param>
/// <param name="accessKey">访问密钥。</param>
/// <param name="secretKey">秘密密钥。</param>
/// <param name="defaultBucket">默认存储桶名。</param>
/// <param name="useSsl">是否启用 HTTPS;为 null 时按 endpoint 前缀自动判断(默认不启用)。</param>
public MinioFileHelper(string endpoint, string accessKey, string secretKey, string defaultBucket,
bool? useSsl = null)
: this(BuildClient(endpoint, accessKey, secretKey, useSsl), defaultBucket) {
}

/// <summary>使用已有的客户端创建工具类,便于依赖注入或自定义配置。</summary>
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 存储桶操作
/// <summary>列出账号下所有存储桶。</summary>
public async Task<IReadOnlyList<Bucket>> ListBucketsAsync(CancellationToken cancellationToken = default) {
var result = await _client.ListBucketsAsync(cancellationToken).ConfigureAwait(false);
return result.Buckets.ToList();
}

/// <summary>判断存储桶是否存在。</summary>
public Task<bool> BucketExistsAsync(string? bucket = null, CancellationToken cancellationToken = default)
=> _client.BucketExistsAsync(
new BucketExistsArgs().WithBucket(ResolveBucket(bucket)), cancellationToken);

/// <summary>确保存储桶存在,不存在则创建。</summary>
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);
}

/// <summary>删除存储桶(桶必须为空)。</summary>
public Task RemoveBucketAsync(string? bucket = null, CancellationToken cancellationToken = default)
=> _client.RemoveBucketAsync(
new RemoveBucketArgs().WithBucket(ResolveBucket(bucket)), cancellationToken);
#endregion


#region 上传
/// <summary>上传本地文件。</summary>
/// <param name="localFilePath">本地文件路径。</param>
/// <param name="objectName">对象名(可含路径,如 docs/a.txt)。</param>
/// <param name="bucket">存储桶,省略则用默认桶。</param>
/// <param name="contentType">内容类型,省略则按扩展名推断。</param>
/// <param name="progress">上传进度回调。</param>
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);

// 自行管理文件流,避免 SDK 的 WithFileName 长时间占用文件句柄。
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);
}

/// <summary>上传流。若流不可 Seek,必须显式传入 objectSize。</summary>
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 下载
/// <summary>下载对象到本地文件(自动创建目标目录)。</summary>
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);
}

/// <summary>下载对象到指定流(流由调用方负责释放)。</summary>
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);
}

/// <summary>下载对象为字节数组(适合小文件)。</summary>
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 查询与列举
/// <summary>获取对象元信息;对象或桶不存在时返回 null。</summary>
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;
}
}

/// <summary>判断对象是否存在。</summary>
public async Task<bool> ExistsAsync(
string objectName,
string? bucket = null,
CancellationToken cancellationToken = default)
=> await GetObjectInfoAsync(objectName, bucket, cancellationToken).ConfigureAwait(false) is not null;

/// <summary>列举对象。</summary>
/// <param name="prefix">前缀过滤,如 docs/。</param>
/// <param name="recursive">是否递归列出子目录,默认 true。</param>
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 删除与复制
/// <summary>删除单个对象。</summary>
public Task RemoveObjectAsync(
string objectName,
string? bucket = null,
CancellationToken cancellationToken = default) {
ValidateObjectName(objectName);
return _client.RemoveObjectAsync(
new RemoveObjectArgs().WithBucket(ResolveBucket(bucket)).WithObject(objectName),
cancellationToken);
}

/// <summary>批量删除对象,返回删除失败的错误列表(为空表示全部成功)。</summary>
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();
}

/// <summary>
/// 复制对象(支持跨桶)。
/// SDK 7.0.0 的 CopyObjectAsync 在部分服务端会报签名不匹配,
/// 因此这里用临时文件中转实现;复制大文件时会占用等量的临时磁盘空间。
/// </summary>
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
/// <summary>生成临时下载链接。</summary>
/// <param name="expirySeconds">有效期(秒),范围 1 ~ 604800。</param>
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));
}

/// <summary>生成临时上传链接,供客户端直传使用。</summary>
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
}

测试

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
using MinioDemo;


const string endpoint = "xxx:xxx";
const string accessKey = "xxx";
const string secretKey = "xxx";
const string bucketName = "bucket01";

var minioHelper = new MinioFileHelper(endpoint, accessKey, secretKey, bucketName);


// 列举存储桶
foreach (var bucket in await minioHelper.ListBucketsAsync())
Console.WriteLine($"桶: {bucket.Name} 创建时间: {bucket.CreationDateDateTime}");

// 确保存储桶存在,没有就会创建
await minioHelper.EnsureBucketAsync();

// 移除文件,即使不存在也不会报错
await minioHelper.RemoveObjectAsync("demo.txt");

// 上传文件,同名直接覆盖
const string objectName = "demo.txt";
const string localUploadPath = @"D:\demo.txt";
if (File.Exists(localUploadPath)) {
var uploaded = await minioHelper.UploadFileAsync(localUploadPath, objectName);
Console.WriteLine($"上传成功: {uploaded.ObjectName},{uploaded.Size} 字节,ETag={uploaded.Etag}");
} else {
Console.WriteLine($"跳过上传: 本地文件 {localUploadPath} 不存在");
}

// 查询对象信息
var stat = await minioHelper.GetObjectInfoAsync(objectName);
Console.WriteLine(stat is null
? $"对象 {objectName} 不存在"
: $"对象 {objectName}: {stat.Size} 字节,修改时间 {stat.LastModified:yyyy-MM-dd HH:mm:ss}");

// 列举对象
foreach (var item in await minioHelper.ListObjectsAsync())
Console.WriteLine($"对象: {item.Key} {item.Size} 字节");

// 生成 1 小时有效的临时下载链接
string getUrl = await minioHelper.GetPresignedGetUrlAsync(objectName);
Console.WriteLine($"临时下载链接: {getUrl}");

// 下载文件到本地
await minioHelper.DownloadFileAsync(objectName, @"D:\download\demo.txt");

// 复制文件
await minioHelper.CopyObjectAsync(objectName, "copy/demo.txt");
await minioHelper.RemoveObjectAsync("copy/demo.txt");

// 临时上传链接
string putUrl = await minioHelper.GetPresignedPutUrlAsync(objectName);
Console.WriteLine($"临时上传链接: {putUrl}");

(转载本站文章请注明作者和出处lihaohello.top,请勿用于任何商业用途)