😅 备忘Minio接入,方便以后用到复制(或者参考)
json "Minio": {
"Endpoint": "minio-oss.xxxxx.com",
"Region": "minio-oss.xxxxx.com",
"AccessKey": "xxxxx",
"SecretKey": "xxxxx",
"BucketName": "xxxxx",
"FileURL": "https://minio-oss.xxxxx.com"
}
c#
MinioOptions minioOptions = new();
builder.Configuration.GetSection("Minio").Bind(minioOptions);
builder.Services.AddMinio(options => options = minioOptions);
C# public partial class MinioServices
{
public MinioClient _client { get; set; }
public MinioOptions _minioOptions { get; set; }
/// <summary>
/// 桶名称
/// </summary>
private readonly string _bucketName = "";
/// <summary>
/// 文件域名前缀
/// </summary>
private readonly string _fileUrl = "";
public MinioServices(MinioClient client, IOptions<MinioOptions> minioOptions)
{
_client = client;
_minioOptions = minioOptions.Value;
_bucketName = App.Configuration["Minio:BucketName"]
?? throw Oops.Bah(5000, "缺少Minio:BucketName 配置"); ;
_fileUrl = App.Configuration["Minio:FileUrl"]
?? throw Oops.Bah(5000, "缺少Minio:FileUrl 配置");
}
//获取图片的返回类型
public static Dictionary<string, string> contentTypDict = new Dictionary<string, string> {
{"bmp","image/bmp" },
{"jpg","image/jpeg"},
{"jpeg","image/jpeg"},
{"jpe","image/jpeg"},
{"png","image/png"},
{"gif","image/gif"},
{"ico","image/x-ico"},
{"tif","image/tiff"},
{"tiff","image/tiff"},
{"fax","image/fax"},
{"wbmp","image/vnd.wap.wbmp"},
{"rp","image/vnd.rn-realpix"} };
/// <summary>
/// 上传图片
/// </summary>
/// <param name="file">文件</param>
/// <returns></returns>
public async Task<FileDto> UploadImageAsync(FormFileCollection file)
{
//获得文件扩展名
string fileNameEx = System.IO.Path.GetExtension(file[0].FileName).Replace(".", "");
var a = file[0].ContentType;
//是否是图片,现在只能是图片上传 文件类型 或扩展名不一致则返回
if (contentTypDict.Values.FirstOrDefault(c => c == file[0].ContentType.ToLower()) == null || contentTypDict.Keys.FirstOrDefault(c => c == fileNameEx) == null)
{
throw Oops.Bah(3100, "图片格式不正确");
}
else
{
var contentType = contentTypDict.Values.FirstOrDefault(c => c == file[0].ContentType.ToLower());
return await UploadAsync(file, contentType);
}
}
public async Task<FileDto> UploadFileAsync(FormFileCollection file)
{
//获得文件扩展名
string fileNameEx = System.IO.Path.GetExtension(file[0].FileName).Replace(".", "");
return await UploadAsync(file, null);
}
/// <summary>
/// 上传
/// </summary>
/// <param name="file">文件</param>
/// <param name="contentType">文件类型</param>
/// <returns></returns>
public async Task<FileDto> UploadAsync(FormFileCollection file, string contentType)
{
//存储桶名
string bucketName = _bucketName;
var result = new FileDto();
await CreateBucket(bucketName);
var newFileName = CreateNewFileName(file[0].FileName);
//var metaData = new Dictionary<string, string>
// {
// { "Test-Metadata", "Test Test" }
// };
var filestream = file[0].OpenReadStream();
PutObjectArgs args = new PutObjectArgs()
.WithBucket(bucketName)
.WithObject(newFileName)
.WithStreamData(filestream)
.WithObjectSize(filestream.Length)
.WithContentType(contentType);
await _client.PutObjectAsync(args);
result.Url = $"{_fileUrl}/{bucketName}/{newFileName}";
return result;
}
public async Task<FileDto> UploadPdf(Stream file)
{
FileDto result = new FileDto();
//存储桶名
string bucketName = _bucketName;
await CreateBucket(bucketName);
var newFileName = CreateNewFileName("xxx.pdf");
PutObjectArgs args = new PutObjectArgs()
.WithBucket(bucketName)
.WithObject(newFileName)
.WithStreamData(file)
.WithObjectSize(file.Length)
.WithContentType("application/pdf");
await _client.PutObjectAsync(args);
result.Url = $"{_fileUrl}/{bucketName}/{newFileName}";
return result;
}
/// <summary>
/// 创建桶
/// </summary>
/// <param name="bucketName"></param>
/// <returns></returns>
private async Task CreateBucket(string bucketName)
{
BucketExistsArgs args = new BucketExistsArgs()
.WithBucket(bucketName);
var found = await _client.BucketExistsAsync(args);
if (!found)
{
await _client.MakeBucketAsync(
new MakeBucketArgs()
.WithBucket(bucketName)
);
}
}
/// <summary>
/// 创建新的文件名
/// </summary>
/// <param name="bucketName"></param>
/// <param name="oldFileName"></param>
/// <returns></returns>
private string CreateNewFileName(string oldFileName)
{
var dt = Guid.NewGuid().ToString().Replace("-", "").Substring(10) + DateTimeOffset.Now.ToUnixTimeSeconds();
var extensions = Path.GetExtension(oldFileName);
var newFileName = $"{DateTime.Today.ToString("yyyy-MM-dd")}/{dt}{extensions}";
return newFileName;
}
/// <summary>
/// 获取上传路径
/// </summary>
/// <param name="fileName"></param>
/// <param name="expiry">失效时间(秒)</param>
/// <returns></returns>
public async Task<string> GetUploadFileUrl(string fileName, int expiry = 1000)
{
//存储桶名
string bucketName = _bucketName;
await CreateBucket(bucketName);
var newFileName = CreateNewFileName(fileName);
PresignedPutObjectArgs args = new PresignedPutObjectArgs()
.WithBucket(bucketName)
.WithObject(newFileName)
.WithExpiry(expiry);
string presignedUrl = await _client.PresignedPutObjectAsync(args);
return presignedUrl;
}
}
本文作者:宁骑
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 MIT 许可协议。转载请注明出处!