Minio+SpringBoot 的实际场景应用

pom

      <!-- minio 文件操作-->
        <dependency>
            <groupId>io.minio</groupId>
            <artifactId>minio</artifactId>
            <version>7.0.2</version>
        </dependency>

yml

minio:
  url: http://127.0.0.1:2020
  accessKey: admin
  secretKey: 123456
  bucketName: minio-files

utils

package com.xacf.athena.science.core.util;

import com.xacf.athena.science.core.util.properties.MinioProperties;
import io.minio.MinioClient;
import io.minio.ObjectStat;
import io.minio.PutObjectOptions;
import io.minio.messages.Bucket;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;

/**
 * @author wzq
 * @event     文件服务器工具类-minio
 * @describe
 * @Data on 2021-12-10 08:53:57
 */
@Slf4j
@Component
public class MinioUtil {

    @Autowired
    MinioProperties minioProperties;

    private static MinioClient minioClient;


    /**
     * 初始化minio配置
     *
     * @param :
     * @return: void
     * @date : 2020/8/16 20:56
     */
    @PostConstruct
    public void init() {
        try {
            minioClient = new MinioClient(minioProperties.getUrl(), minioProperties.getAccessKey(),
                    minioProperties.getSecretKey());
            createBucket(minioProperties.getBucketName());
        } catch (Exception e) {
            e.printStackTrace();
            log.error("初始化minio配置异常: 【{}】", e.fillInStackTrace());
        }
    }

    /**
     * 判断 bucket是否存在
     *
     * @param bucketName:
     *            桶名
     * @return: boolean
     * @date : 2020/8/16 20:53
     */
    @SneakyThrows(Exception.class)
    public static boolean bucketExists(String bucketName) {
        return minioClient.bucketExists(bucketName);
    }

    /**
     * 创建 bucket
     *
     * @param bucketName:
     *            桶名
     * @return: void
     * @date : 2020/8/16 20:53
     */
    @SneakyThrows(Exception.class)
    public static void createBucket(String bucketName) {
        boolean isExist = minioClient.bucketExists(bucketName);
        if (!isExist) {
            minioClient.makeBucket(bucketName);
        }
    }
    /**
     * 上传文件
     * @param bucketName
     * @param fileName
     * @param multipartFile
     */
    public String uploadFile(String bucketName, String fileName, MultipartFile multipartFile) throws Exception {
        minioClient.putObject(bucketName,fileName,multipartFile.getInputStream(),new PutObjectOptions(multipartFile.getSize(),-1));
        String fileUrl = minioProperties.getUrl()+"/"+bucketName+"/"+fileName;
        return fileUrl;
    }
    /**
     * 获取全部bucket
     *
     * @param :
     * @return: java.util.List<io.minio.messages.Bucket>
     * @date : 2020/8/16 23:28
     */
    @SneakyThrows(Exception.class)
    public static List<Bucket> getAllBuckets() {
        return minioClient.listBuckets();
    }

    /**
     * 文件上传
     *
     * @param bucketName:
     *            桶名
     * @param fileName:
     *            文件名
     * @param filePath:
     *            文件路径
     * @return: void
     * @date : 2020/8/16 20:53
     */
    @SneakyThrows(Exception.class)
    public static String upload(String bucketName, String fileName, String filePath) {
        minioClient.putObject(bucketName, fileName, filePath, null);
        return fileName;
    }

    /**
     * 文件上传
     *
     * @param bucketName:
     *            桶名
     * @param fileName:
     *            文件名
     * @param stream:
     *            文件流
     * @return: java.lang.String : 文件url地址
     * @date : 2020/8/16 23:40
     */
    @SneakyThrows(Exception.class)
    public static String upload(String bucketName, String fileName, InputStream stream) {
        minioClient.putObject(bucketName, fileName, stream, new PutObjectOptions(stream.available(), -1));
        //return getFileUrl(bucketName, fileName);
        return fileName;
    }

    /**
     * 文件上传
     *
     * @param bucketName:
     *            桶名
     * @param file:
     *            文件
     * @return: java.lang.String : 文件url地址
     * @date : 2020/8/16 23:40
     */
    @SneakyThrows(Exception.class)
    public static String upload(String bucketName, MultipartFile file) {
        final InputStream is = file.getInputStream();
        final String fileName = file.getOriginalFilename();
        minioClient.putObject(bucketName, fileName, is, new PutObjectOptions(is.available(), -1));
        is.close();
        //return getFileUrl(bucketName, fileName);
        return fileName;
    }

    /**
     * 删除文件
     *
     * @param bucketName:
     *            桶名
     * @param fileName:
     *            文件名
     * @return: void
     * @date : 2020/8/16 20:53
     */
    @SneakyThrows(Exception.class)
    public static void deleteFile(String bucketName, String fileName) {
        minioClient.removeObject(bucketName, fileName);
    }

    /**
     * 下载文件
     *
     * @param bucketName:
     *            桶名
     * @param fileName:
     *            文件名
     * @param response:
     * @return: void
     * @date : 2020/8/17 0:34
     */
    @SneakyThrows(Exception.class)
    public static void download(String bucketName, String fileName, HttpServletResponse response) {
        // 获取对象的元数据
        final ObjectStat stat = minioClient.statObject(bucketName, fileName);
        response.setContentType(stat.contentType());
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
        InputStream is = minioClient.getObject(bucketName, fileName);
        IOUtils.copy(is, response.getOutputStream());
        is.close();
    }

    /**
     * 获取minio文件的下载地址
     *
     * @param bucketName:
     *            桶名
     * @param fileName:
     *            文件名
     * @return: java.lang.String
     * @date : 2020/8/16 22:07
     */
    @SneakyThrows(Exception.class)
    public static String getFileUrl(String bucketName, String fileName) {
        return minioClient.presignedGetObject(bucketName, fileName);
    }

}
MinioProperties
package com.xacf.athena.science.core.util.properties;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

/**
 * @author wzq
 * @event  文件服务器属性类-minio
 * @describe
 * @Data on 2021/9/3  10:54
 */
@Data
@Configuration
@ConfigurationProperties(prefix = "minio")
public class MinioProperties {
    /**
     * minio地址+端口号
     */
    private String url;

    /**
     * minio用户名
     */
    private String accessKey;

    /**
     * minio密码
     */
    private String secretKey;

    /**
     * 文件桶的名称
     */
    private String bucketName;
}

Controller

package com.xacf.athena.science.modular.material.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xacf.athena.science.core.annotion.BusinessLog;
import com.xacf.athena.science.core.enums.LogAnnotionOpTypeEnum;
import com.xacf.athena.science.core.pojo.response.ResponseData;
import com.xacf.athena.science.core.pojo.response.SuccessResponseData;
import com.xacf.athena.science.core.util.MinioUtil;
import com.xacf.athena.science.core.util.properties.MinioProperties;
import com.xacf.athena.science.modular.finance.param.AsFinancialBookkeepingParam;
import com.xacf.athena.science.modular.material.param.AsMaterialParam;
import com.xacf.athena.science.modular.index.param.DownloadParam;
import com.xacf.athena.science.modular.material.service.AsMaterialService;
import com.xacf.athena.science.modular.record.param.AsFileDownloadRecordParam;
import com.xacf.athena.science.modular.record.service.AsFileDownloadRecordService;
import com.xacf.athena.science.sys.core.enums.BaseEnum;
import com.xacf.athena.science.sys.core.enums.FileTypeEnum;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.net.URLDecoder;

/**
 * @author wzq
 * @event
 * @describe
 * @Data on 2022-1-6 14:04:04
 */
@RestController
@RequestMapping("/asMaterial")
@Api(value = "asMaterial", tags = "资料管理")
public class AsMaterialController {

    @Autowired
    private AsMaterialService asMaterialService;

    @Autowired
    private AsFileDownloadRecordService asFileDownloadRecordService;

    @Autowired
    MinioProperties minioProperties;

    @Autowired
    MinioUtil minioUtil;


    /**
     * auther wzq
     * @param multipartFile MultipartFile
     * @event 资料管理上传
     * @Data on 2021-12-10 09:24:22
     * */
    @ApiOperation(value = "资料管理上传",notes = "资料管理上传")
    @PostMapping("/upload")
    public ResponseData upload(@RequestPart("file") MultipartFile multipartFile){
        try {
            String url = minioUtil.uploadFile(minioProperties.getBucketName(),"material/"+multipartFile.getOriginalFilename(),multipartFile);
            return new SuccessResponseData(url);
        }catch (Exception e){
            e.printStackTrace();
            return new SuccessResponseData();
        }
    }

    /**
     * auther wzq
     * @param downloadParam: 下载参数
     * @event 资料管理下载
     * @Data on 2021-12-10 10:53:15
     * */
    @ApiOperation(value = "资料管理下载",notes = "资料管理下载")
    @PostMapping("/download")
    @BusinessLog(title = "资料管理下载", opType = LogAnnotionOpTypeEnum.QUERY)
    public void download(@RequestBody @Validated(DownloadParam.add.class)DownloadParam downloadParam, HttpServletResponse response){
        try {
            MinioUtil.download("athena-science","material/"+new File(URLDecoder.decode(downloadParam.getUrlPath())).getName(),response);
            //文件下载记录
            /*AsFileDownloadRecordParam vo = new AsFileDownloadRecordParam();
            vo.setDownloadType(FileTypeEnum.TWO.getCode());
            vo.setDownloadUrl(URLDecoder.decode(downloadParam.getUrlPath()));
            asFileDownloadRecordService.add(vo);*/
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值