105 lines
3.2 KiB
C#
105 lines
3.2 KiB
C#
using Bunny.Common;
|
|
using Bunny.Common.Connect;
|
|
using Microsoft.AspNetCore.Http;
|
|
using Minio;
|
|
using Minio.DataModel;
|
|
using Minio.DataModel.Args;
|
|
using Minio.DataModel.Result;
|
|
|
|
namespace Bunny.Service.IService.Service;
|
|
|
|
public class MinioService : IMinioService
|
|
{
|
|
private readonly IMinioClient _minioContext = MinioContext.MinioClient!;
|
|
|
|
/// <summary>
|
|
/// 上传文件
|
|
/// </summary>
|
|
/// <param name="file">文件内容</param>
|
|
/// <param name="filepath"></param>
|
|
public async void SaveMinioFile(IFormFile? file, string filepath)
|
|
{
|
|
if (file == null)
|
|
{
|
|
Console.WriteLine("文件未上传");
|
|
return;
|
|
}
|
|
|
|
var fileName = file.FileName;
|
|
var contentType = file.ContentType;
|
|
await _minioContext.PutObjectAsync(new PutObjectArgs()
|
|
.WithBucket(MinioContext.BucketName)
|
|
.WithObject($"{filepath}/{fileName}")
|
|
.WithStreamData(file.OpenReadStream())
|
|
.WithContentType(contentType)
|
|
.WithObjectSize(file.Length)
|
|
);
|
|
}
|
|
|
|
/// <summary>
|
|
/// 查询所有的桶
|
|
/// </summary>
|
|
/// <returns>桶列表</returns>
|
|
public ListAllMyBucketsResult GetAllMyBuckets()
|
|
{
|
|
return _minioContext!.ListBucketsAsync().Result;
|
|
}
|
|
|
|
/// <summary>
|
|
/// 获取文件信息
|
|
/// </summary>
|
|
/// <param name="filename">文件名</param>
|
|
/// <param name="bucketName">桶名称</param>
|
|
/// <returns>ObjectStat</returns>
|
|
public ObjectStat GetObjectStat(string filename, string bucketName)
|
|
{
|
|
var objectAsync = _minioContext.GetObjectAsync(new GetObjectArgs()
|
|
.WithBucket(bucketName)
|
|
.WithObject(filename)
|
|
.WithFile(filename)
|
|
).Result;
|
|
|
|
return objectAsync;
|
|
}
|
|
|
|
/// <summary>
|
|
/// 获取文件路径
|
|
/// </summary>
|
|
/// <param name="filename">文件名</param>
|
|
/// <param name="bucketName">桶名称</param>
|
|
/// <returns>文件地址</returns>
|
|
public string GetObjectPath(string filename, string bucketName)
|
|
{
|
|
var url = AppSettings.GetConfig("Minio:Url");
|
|
return $"{url}/{bucketName}/{filename}";
|
|
}
|
|
|
|
/// <summary>
|
|
/// 下载文件
|
|
/// </summary>
|
|
/// <param name="filename">文件名</param>
|
|
/// <param name="bucketName">桶名称</param>
|
|
/// <returns>下载文件</returns>
|
|
public async Task<byte[]> DownloadObject(string filename, string bucketName)
|
|
{
|
|
var url = AppSettings.GetConfig("Minio:Url");
|
|
var downloadUrl = $"http://{url}/{bucketName}/{filename}";
|
|
using var client = new HttpClient();
|
|
var responseMessage = await client.GetAsync(downloadUrl);
|
|
if (!responseMessage.IsSuccessStatusCode) return [];
|
|
var buffer = await responseMessage.Content.ReadAsByteArrayAsync();
|
|
return buffer;
|
|
}
|
|
|
|
public IAsyncEnumerable<Item> ListObject(string? filepath, string bucketName)
|
|
{
|
|
return _minioContext
|
|
.ListObjectsEnumAsync(
|
|
new ListObjectsArgs()
|
|
.WithBucket(bucketName)
|
|
.WithPrefix(filepath)
|
|
.WithVersions(false)
|
|
.WithRecursive(true)
|
|
);
|
|
}
|
|
} |