SpringBoot上传文件到Minio服务器,支持批量上传

10 篇文章 3 订阅

前言

本文主要介绍如何使用SpringBoot上传到minio服务器。

没什么可多说的,公司用什么咱们开发研究什么就完事了。直接分享核心代码。

单个文件上传

minio依赖

  <!--  minio依赖   -->
        <dependency>
            <groupId>io.minio</groupId>
            <artifactId>minio</artifactId>
            <version>8.2.1</version>
        </dependency>

配置文件

首先是核心的参数,包括服务器minio地址,以及用户名密码,使用的桶名称

 # 配置minio文件上传的几个核心参数
  minio:
    minio_url: xxx
    minio_name: xxx
    minio_pass: xxx
    bucketName: xxxx

controller代码

如果只需要上传文件,只需要MultipartFile参数就够了。我的这几个参数都是为了完成业务逻辑

	@ApiOperation(value = "身份信息表-附件信息-上传文件", notes = "身份信息表-附件信息-上传文件")
    @PostMapping(value = "/upload")
    public Result<?> upload(MultipartFile file, Integer fileTypeDic, Integer fileCategoryDic) throws Exception {
        return identityFileInfoService.uploadMinio(file, fileTypeDic, fileCategoryDic);
    }

service代码

   /**
     * @Author 魏一鹤
     * @Description 上传到minio服务器
     * @Date 10:51 2022/12/20
     */
    Result<?> uploadMinio(MultipartFile file, Integer fileTypeDic, Integer fileCategoryDic) throws Exception;

serviceImpl代码

做主要的代码就是这在里,获取配置文件里面的几个参数。初始化一个minio客户端

这里面方法的部分参数和代码都是为了满足我个人需求,比如创建存放文件的年月目录层级,获取文件前后缀等。根据自己的需求灵活改变即可。

注意:一下代码进行了部分代码割舍,直接复制可能会报错,根据自己的需求灵活改变即可。

package org.jeecg.front.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.util.filter.FileTypeFilter;
import org.jeecg.common.util.filter.StrAttackFilter;
import org.jeecg.front.entity.IdentityFileInfo;
import org.jeecg.front.service.IdentityFileInfoService;
import org.jeecg.modules.common.FileUtils;
import org.jeecg.modules.common.IOUtils;
import org.jeecg.modules.mapper.IdentityFileInfoMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Calendar;
import java.util.Date;

import static org.jeecg.modules.common.ResultCodeStatusEnum.FAIL;
import static org.jeecg.modules.common.ResultCodeStatusEnum.SUCCESS;

/**
 * @Author 魏一鹤
 * @Description 身份信息表-附件信息service接口实现类
 * @Date 2022/12/19
 **/
@Service
public class IdentityFileInfoServiceImpl extends ServiceImpl<IdentityFileInfoMapper, IdentityFileInfo> implements IdentityFileInfoService {
    // 上传路径
    @Value(value = "${jeecg.minio.minio_url}")
    private String minioUrl;
    // 上传类型 minio
    @Value(value = "${jeecg.uploadType}")
    private String uploadType;
    // 桶名称
    @Value(value = "${jeecg.minio.bucketName}")
    private String bucketName;
    // minio用户名
    @Value(value = "${jeecg.minio.minio_name}")
    private String minioName;
    // minio密码
    @Value(value = "${jeecg.minio.minio_pass}")
    private String minioPass;
    // minio客户端
    private static MinioClient minioClient = null;
    // 系统路径 
    private String sysPath = "";

    /**
     * @Author 魏一鹤
     * @Description 上传到minio服务器
     * @Date 10:51 2022/12/20
     */
    @Override
    public Result<?> uploadMinio(MultipartFile file, Integer identityInfoId, Integer fileTypeDic) throws Exception {
        Result<IdentityFileInfo> result = new Result<>();
        Calendar calendar = Calendar.getInstance();
        // 当前年份,用于拼接系统路径
        int year = calendar.get(Calendar.YEAR);
        // 当前月份,注意加1,用于拼接系统路径
        int month = calendar.get(Calendar.MONTH) + 1;
        // 格式化时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String time = sdf.format(new Date());
        // 上传后的完整路径
        String filePath = "";
        // 文件大小
        long size = file.getSize();
        // 拼接的系统上传路径
        String spliceSysPath = sysPath + year + "/" + month;
        spliceSysPath = StrAttackFilter.filter(spliceSysPath);
        FileTypeFilter.fileTypeFilter(file);
        InputStream stream = null;
        try {
            // 初始化minio客户端
            initMinio(minioUrl, minioName, minioPass);
            stream = file.getInputStream();
            // 获取原文件名 这个文件名用于文件路径拼接
            String orgName = file.getOriginalFilename();
            String objectName = null;
            // 获取原文件名 这个文件名就是原文件名
            String originalFilename = null;
            // 文件前缀
            String prefix = null;
            // 文件后缀
            String suffix = null;
            if (StringUtils.isNotBlank(orgName)) {
                originalFilename = file.getOriginalFilename();
                prefix = orgName.substring(0, orgName.lastIndexOf("."));
                // 文件后缀
                suffix = orgName.substring(orgName.lastIndexOf("."));
                objectName = spliceSysPath + "/" + prefix + "_" + time + suffix;
            }
            PutObjectArgs objectArgs = PutObjectArgs.builder()
                    .object(objectName)
                    .bucket(bucketName)
                    .contentType("application/octet-stream")
                    .stream(stream, stream.available(), -1).build();
            minioClient.putObject(objectArgs);
            filePath = minioUrl + bucketName + "/" + objectName;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            if (stream != null) {
                stream.close();
            }
        }
        return result;
    }

 


    /**
     * 初始化客户端
     *
     * @param minioUrl
     * @param minioName
     * @param minioPass
     * @return
     */
    private static MinioClient initMinio(String minioUrl, String minioName, String minioPass) {
        if (minioClient == null) {
            try {
                minioClient = MinioClient.builder()
                        .endpoint(minioUrl)
                        .credentials(minioName, minioPass)
                        .build();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return minioClient;
    }


}

测试

这样访问接口的url,选择File类型的文件,就能进行文件上传了:

在这里插入图片描述

在桶里面也是可以看到的

在这里插入图片描述

批量文件上传

如果想要进行批量上传,也很简单。只需要把文件改为数组的格式即可:

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

核心代码如下:

Result<?> batchUpload(MultipartFile[] files) throws Exception;

 public Result<?> batchUpload(MultipartFile[] files) throws Exception {
        Result<String> result = new Result<>();
        Calendar calendar = Calendar.getInstance();
        // 当前年份,用于拼接系统路径
        int year = calendar.get(Calendar.YEAR);
        // 当前月份,注意加1,用于拼接系统路径
        int month = calendar.get(Calendar.MONTH) + 1;
        // 格式化时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String time = sdf.format(new Date());
        // 上传后的完整路径
        String filePath = "";
        // 拼接的系统上传路径
        String spliceSysPath = sysPath + year + "/" + month;
        spliceSysPath = StrAttackFilter.filter(spliceSysPath);
        InputStream stream = null;
        try {
            for (MultipartFile file : files) {
                FileTypeFilter.fileTypeFilter(file);
                // 初始化minio客户端
                initMinio(minioUrl, minioName, minioPass);
                stream = file.getInputStream();
                // 获取原文件名 这个文件名用于文件路径拼接
                String orgName = file.getOriginalFilename();
                String objectName = null;
                // 文件前缀
                String prefix = null;
                // 文件后缀
                String suffix = null;
                if (StringUtils.isNotBlank(orgName)) {
                    prefix = orgName.substring(0, orgName.lastIndexOf("."));
                    // 文件后缀
                    suffix = orgName.substring(orgName.lastIndexOf("."));
                    objectName = spliceSysPath + "/" + prefix + "_" + time + suffix;
                }
                PutObjectArgs objectArgs = PutObjectArgs.builder()
                        .object(objectName)
                        .bucket(bucketName)
                        .contentType("application/octet-stream")
                        .stream(stream, stream.available(), -1).build();
                minioClient.putObject(objectArgs);
                filePath = minioUrl + bucketName + "/" + objectName;
            }
            result.setMessage(SUCCESS.getDesc());
            result.setSuccess(true);
            result.setCode(SUCCESS.getCode());
            result.setResult(filePath);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.setMessage(FAIL.getDesc());
            result.setCode(FAIL.getCode());
            result.setSuccess(false);
        } finally {
            if (stream != null) {
                stream.close();
            }
        }
        return result;
    }

测试

在这里插入图片描述

  • 3
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小花皮猪

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值