ASP.NET Core上传文件到minio
1.用到的依赖包—Minio
使用命令添加依赖,或者使用Nugui搜索minio依赖后添加到指定项目中
dotnet add package Minio --version 6.0.5
我这里是使用了JetBrains Rider,这工具其实也挺好使的,尤其对于我本身写java的人来说,很容易习惯,无非就是占用内存比起vs code要高不少。
如果是用vs code,需要先安装nug包管理插件——NuGet Package Manager GUI
使用command+shift+p(macOS)或者ctrl+shift+p(Windows),输入nug,然后搜索即可
2.相关代码
[HttpPost("upload/single")][ProducesResponseType(typeof(CommonResult<FileUploadResp>), StatusCodes.Status200OK)][ProducesResponseType(StatusCodes.Status200OK)]public async Task<IActionResult> PostUploadFileMinio(string? bucket, IFormFile file){if (file is not { Length: > 0 }){return Ok(CommonResult<string>.Failed(500, "文件不能为空"));}_service._logger.LogDebug("上传的文件信息==={file}", JsonHelper.Serialize(file));var response = await _service.UploadFile(bucket, file);return Ok(CommonResult<FileUploadResp>.Success("上传成功", response));}
public async Task<FileUploadResp> UploadFile(string? bucket, IFormFile file){bucket ??= "test";try{var safeFileName = Path.GetFileName(file.FileName);safeFileName = GenerateUniqueFileName(safeFileName);await using var stream = file.OpenReadStream();await _minioClient.PutObjectAsync(new PutObjectArgs().WithBucket(bucket).WithObject(safeFileName).WithStreamData(stream).WithObjectSize(file.Length).WithContentType(file.ContentType));var endpoint = _minioClient.Config.Endpoint;if (!Uri.TryCreate(endpoint, UriKind.Absolute, out var uri)){_logger.LogError("minio的endpoint无效==={uri}", uri);throw new ArgumentException("minio端点无效");}var fileUrl = $"{endpoint}/{bucket}/{safeFileName}";var resp = new FileUploadResp(safeFileName, fileUrl);_logger.LogDebug("文件上传成功==={resp}", JsonHelper.Serialize(resp));return resp;}catch (Exception ex){_logger.LogError(ex, "minio文件上传异常");throw new Model.CusException.MinioException(500, "文件上传失败,稍后重试");}}
3.上传测试
在swagger中调用上传接口
控制台日志
浏览器访问minio图片