ASP.NET Core上传文件到minio

1.用到的依赖包---Minio

使用命令添加依赖,或者使用Nugui搜索minio依赖后添加到指定项目中

bash 复制代码
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.相关代码

cs 复制代码
    [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));
    }
cs 复制代码
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图片

相关推荐
期待のcode4 小时前
MyBatisX插件
java·数据库·后端·mybatis·springboot
华仔啊7 小时前
这 10 个 MySQL 高级用法,让你的代码又快又好看
后端·mysql
码事漫谈8 小时前
国产时序数据库崛起:金仓凭什么在复杂场景中碾压InfluxDB
后端
上进小菜猪8 小时前
当时序数据不再“只是时间”:金仓数据库如何在复杂场景中拉开与 InfluxDB 的差距
后端
盖世英雄酱581369 小时前
springboot 项目 从jdk 8 升级到jdk21 会面临哪些问题
java·后端
程序猿DD9 小时前
JUnit 5 中的 @ClassTemplate 实战指南
java·后端
Victor35610 小时前
Netty(14)如何处理Netty中的异常和错误?
后端
Victor35610 小时前
Netty(13)Netty中的事件和回调机制
后端
码事漫谈11 小时前
VS Code 1.107 更新:多智能体协同与开发体验升级
后端