Java实现minio

2023-12-13 04:04:12

配置Dapplication.yml

minio:
  access-key: minioadmin
  secret-key: minioadmin
  bucket-name: file #指定桶名称
  endpoint: http://localhost:9000

实现代码minioContriller.java

package com.setsail.setsailcusserver.controller;

import com.alibaba.fastjson.JSONObject;
import com.setsail.setsailcusserver.service.UserRegisService;
import com.setsail.setsailcusserver.uatils.MinioUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Description:
 * @Title: UserRegisController
 * @Author hello
 * @Date: 2023/4/10 9:49
 * @Version 1.0
 */
@Slf4j
@RestController
@RequestMapping("/minio")
public class minioController {
 
    @Resource
    private MinioUtils minioUtils;
    @Value("${minio.bucket-name}")
    private String bucketName;


    /**
     * 上传
     * @param file
     * @throws Exception
     */
    @GetMapping("uploadFile")
    public void uploadFile(@RequestParam(name = "file", required = false) MultipartFile file, HttpServletRequest request) throws Exception{
        // 桶名称
        String bucketNameParam = request.getParameter("bucketName");
        // 如果没有传同名称默认系统配置桶
        if (StringUtils.isBlank(bucketNameParam)){
            bucketNameParam=bucketName;
        }else {
            if (!minioUtils.createIsBucket(bucketNameParam)){
                return;
            }
        }
        JSONObject jsonObject = minioUtils.uploadFile(file, bucketNameParam);
    }
    /**
     * 桶是否存在
     * @param
     * @throws Exception
     */
    @GetMapping("createIsBucket")
    public void createIsBucket(@RequestParam String bucketName) throws Exception{
         System.out.println(minioUtils.createIsBucket(bucketName));
    }

    /**
     * 删除
     * @param fileName
     * @throws Exception
     */
    @GetMapping("deleteObject")
    public void deleteObject(@RequestParam String  fileName,@RequestParam String  bucketNameParam) throws Exception{
        // 桶不存在
        if (!minioUtils.createIsBucket(bucketNameParam)){
            return;
        }
        minioUtils.deleteObject(fileName,bucketNameParam);
    }

    /**
     * 下载
     *  reakFileName 需要带后缀名
     * @param response
     * @throws Exception
     */
    @GetMapping("downLoad")
    public void downLoad(HttpServletRequest request, HttpServletResponse response) throws Exception{
        String bucketNameParam = request.getParameter("bucketName");
        if (!minioUtils.createIsBucket(bucketNameParam)){
            return;
        }
        String fileName = request.getParameter("fileName");
        minioUtils.downLoad(fileName,fileName,response,request);
    }

    /**
     * 下载图片
     *  reakFileName 需要带后缀名
     * @param response
     * @throws Exception
     */
    @GetMapping("downloadImg")
    public void downloadImg( HttpServletResponse response,HttpServletRequest request) throws Exception{
        String bucketNameParam = request.getParameter("bucketName");
        String fileName = request.getParameter("fileName");
        if (StringUtils.isBlank(bucketNameParam)){
            bucketNameParam=bucketName;
        }else{
            if (!minioUtils.createIsBucket(bucketNameParam)){
                return;
            }
        }
        minioUtils.downloadImg(fileName,fileName,response,bucketNameParam);
    }

    /**
     *查看图片
     * @param response
     * @throws Exception
     */
    @GetMapping("getImage")
    public void getImage( HttpServletResponse response,HttpServletRequest request) throws Exception{
        String bucketNameParam = request.getParameter("bucketName");
        if (!minioUtils.createIsBucket(bucketNameParam)){
            return;
        }
        String fileName = request.getParameter("fileName");
        // 检查该桶下是否存在该图片
        boolean objectExist = minioUtils.isObjectExist(bucketNameParam, fileName);
        if (!objectExist){
            return;
        }

        minioUtils.getImage(fileName,response,request);
    }

    /**
     * 获取权限策略
     * @param
     * @throws Exception
     */
    @GetMapping("getStrategy")
    public void getStrategy() throws Exception{
        minioUtils.getStrategy();
    }
}
MinioConfig.java
package com.setsail.setsailcusserver.config;

import io.minio.MinioClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;



@Configuration
public class MinioConfig {

    @Value("${minio.endpoint}")
    private String endpoint;
    @Value("${minio.access-key}")
    private String accesskey;
    @Value("${minio.secret-key}")
    private String secretKey;
    @Bean
    public MinioClient minioClient(){
        MinioClient minioClient = MinioClient.builder().endpoint(endpoint).
                credentials(accesskey, secretKey).region("china").build();
        return minioClient;
    }
}
MinioUtils工具类
package com.setsail.setsailcusserver.uatils;


import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.common.util.UuidUtils;
import io.minio.*;
import io.minio.errors.MinioException;
import io.minio.messages.Item;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
 * @Author smallhou
 * @Date 2022-08-15 14:31
 * @Version V1.0
 */
@Slf4j
@Component
public class MinioUtils {

    @Autowired
    private  MinioClient minioClient;

    @Value("${minio.bucket-name}")
    private String bucketName;
    /**
     * @Author smallhou
     * @Description //TODO 判断桶存在不存在,不存在创建桶
     * @Date 10:49 2022-08-16
     * @Param [bucketName]
     * @return void
     **/
    @SneakyThrows
    public void createBucket(String bucketName) {
        if (!minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build())) {
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
        }

    }

    /**
     * @Description //TODO 判断桶是否存在
     * @Param [bucketName]
     * @return void
     **/
    @SneakyThrows
    public boolean createIsBucket(String bucketName) {
       return minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
    }

    @SneakyThrows
    public InputStream getObjectInputStream(String objectName,String bucketName){
        GetObjectArgs getObjectArgs = GetObjectArgs.builder()
                .bucket(bucketName)
                .object(objectName)
                .build();
        return minioClient.getObject(getObjectArgs);
    }

    /**
     * 上传文件
     *
     * @param file       文件
     * @param bucketName 存储桶
     * @return
     */
    public JSONObject uploadFile(MultipartFile file, String bucketName) throws Exception {
        JSONObject res = new JSONObject();
        res.put("code", 0);
        // 判断上传文件是否为空
        if (null == file || 0 == file.getSize()) {
            res.put("msg", "上传文件不能为空");
            return res;
        }
        try {
            // 判断存储桶是否存在
            createBucket(bucketName);
            // 文件名
            String originalFilename = file.getOriginalFilename();

            // 新的文件名 = 存储桶名称_时间戳.后缀名
            String fileName = bucketName + "_" + System.currentTimeMillis() + originalFilename.substring(originalFilename.lastIndexOf("."));
            InputStream inputStream = file.getInputStream();
            PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                    .bucket(bucketName)
                    .object(fileName)
                    .contentType(  file.getContentType())
                    .stream(inputStream, inputStream.available(), -1)
                    .build();
            this.minioClient.putObject(putObjectArgs);
            // 开始上传
            res.put("code", 1);
            res.put("msg",  bucketName + "/" + fileName);
            res.put("bucket", bucketName);
            res.put("fileName", fileName);
            return res;
        }  catch (Exception e) {
            log.error("上传文件失败:{}", e.getMessage());
        }
        res.put("msg", "上传失败");
        return res;
    }

    public JSONObject uploadFile(JSONObject fileObj) throws Exception {
        JSONObject res = new JSONObject();
        res.put("code", 0);
        // 判断上传文件是否为空
        if (null == fileObj ) {
            res.put("msg", "上传文件不能为空");
            return res;
        }
        InputStream is=null;
        try {
            // 判断存储桶是否存在
            createBucket(bucketName);
            // 文件名
            String originalFilename = fileObj.getString("originalFilename");
            // 新的文件名 = 存储桶名称_时间戳.后缀名
            String fileName = bucketName + "_" + UuidUtils.generateUuid() + originalFilename.substring(originalFilename.lastIndexOf("."));
            // 开始上传 文件的绝对路径
            is=new FileInputStream(fileObj.getString("inputStream"));
            PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                    .bucket(bucketName)
                    .object(fileName)
                    .contentType(fileObj.getString("contentType"))
                    .stream(is, is.available(), -1)
                    .build();
            this.minioClient.putObject(putObjectArgs);

            res.put("code", 1);
            res.put("msg",  bucketName + "/" + fileName);
            res.put("bucket", bucketName);
            res.put("fileName", fileName);
            return res;
        }  catch (Exception e) {
            e.printStackTrace();
            log.error("上传文件失败:{}", e.getMessage());
        }finally {
            is.close();
        }
        res.put("msg", "上传失败");
        return res;
    }

    public void downLoad(String fileName,String realFileName, HttpServletResponse response, HttpServletRequest request) {
        InputStream is=null;
        OutputStream os =null;
        String bucketNameParam = request.getParameter("bucketName");
        if (StringUtils.isBlank(bucketNameParam)){
            bucketNameParam=bucketName;
        }
        try {
            is=getObjectInputStream(fileName,bucketNameParam);
            if(is!=null){
                byte buf[] = new byte[1024];
                int length = 0;
                String codedfilename = "";
                String agent = request.getHeader("USER-AGENT");
                System.out.println("agent:" + agent);
                if ((null != agent && -1 != agent.indexOf("MSIE")) || (null != agent && -1 != agent.indexOf("Trident"))) {
                    String name = URLEncoder.encode(realFileName, "UTF8");
                    codedfilename = name;
                } else if (null != agent && -1 != agent.indexOf("Mozilla")) {
                    codedfilename = new String(realFileName.getBytes("UTF-8"), "iso-8859-1");
                } else {
                    codedfilename = new String(realFileName.getBytes("UTF-8"), "iso-8859-1");
                }
                response.reset();
                response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(realFileName.substring(realFileName.lastIndexOf("/") + 1), "UTF-8"));
                response.setContentType("application/x-msdownload");
                response.setCharacterEncoding("UTF-8");
                os = response.getOutputStream();
                // 输出文件
                while ((length = is.read(buf)) > 0) {
                    os.write(buf, 0, length);
                }
                // 关闭输出流
                os.close();

            }else{
                log.error("下载失败");
            }
        }catch (Exception e){
            e.printStackTrace();
            log.error("错误:"+e.getMessage());
        }finally {
            if(is!=null){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(os!=null){
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public void downloadImg(String fileName,String realFileName, HttpServletResponse httpResponse,String bucketNameParam) {

        try{
            //imgBucket--桶名称  filename-- 图片名称
            InputStream files = minioClient.getObject(bucketNameParam, fileName);
            InputStream ism = new BufferedInputStream(files);
            // 调用statObject()来判断对象是否存在。
            // 如果不存在, statObject()抛出异常,
            // 否则则代表对象存在
            minioClient.statObject(bucketNameParam, fileName);
            byte buf[] = new byte[1024];
            int length = 0;
            httpResponse.reset();
            //Content-disposition 是 MIME 协议的扩展,MIME 协议指示 MIME 用户代理如何显示附加的文件。
            // Content-disposition其实可以控制用户请求所得的内容存为一个文件的时候提供一个默认的文件名,
            // 文件直接在浏览器上显示或者在访问时弹出文件下载对话框。
            httpResponse.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(realFileName, "UTF-8"));
            httpResponse.setContentType("application/x-msdownload");
            httpResponse.setCharacterEncoding("utf-8");
            OutputStream osm = new BufferedOutputStream(httpResponse.getOutputStream());
            while ((length = ism.read(buf))>0) {
                osm.write(buf,0, length);
            }
            //关闭流
            osm.close();
        } catch (MinioException ex) {
            ex.printStackTrace();
        }  catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     *  图片查看
     * @param fileName
     * @param response
     * @throws IOException
     */
    public void getImage( String fileName, HttpServletResponse response,HttpServletRequest request) throws IOException {
        InputStream in = null;
        String bucketNameParam = request.getParameter("bucketName");
        if (StringUtils.isBlank(bucketNameParam)){
            bucketNameParam=bucketName;
        }
        try {
            in = minioClient.getObject(
                    GetObjectArgs.builder()
                            .bucket(bucketNameParam)
                            .object(fileName)
                            .build()
            );
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (in == null){
            response.sendError(404, "未能找到图片");
        }


        //图片类型
        String[] fileArr = fileName.split("\\.");
        String contentType = "";
        StringBuilder originalFileName = new StringBuilder();
        if (fileArr.length > 1){
            contentType = "image/" + fileArr[fileArr.length - 1];
            for (int i = 0; i < fileArr.length - 1; i++) {
                originalFileName.append(fileArr[i]);
                if (i != fileArr.length - 2){
                    originalFileName.append(".");
                }
            }
        }else {
            contentType = "application/octet-stream";
            originalFileName = new StringBuilder(fileName);
        }

        try {
            response.addHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
            response.addHeader("X-Original-File-Name", originalFileName.toString());
            response.setContentType(contentType);
            ServletOutputStream outputStream = response.getOutputStream();
            IOUtils.copy(in, outputStream);
            outputStream.flush();
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void deleteObject(String fileName,String bucketNameParam) {
        if (StringUtils.isBlank(bucketNameParam)){
            bucketNameParam = bucketName;
        }
        try {
            RemoveObjectArgs removeObjectArgs = RemoveObjectArgs.builder()
                    .bucket(bucketNameParam)
                    .object(fileName)
                    .build();
            minioClient.removeObject(removeObjectArgs);
        }catch (Exception e){
            log.error("错误:"+e.getMessage());
        }
    }


    public void getStrategy() {
        try {
            String bucketPolicy = minioClient.getBucketPolicy(GetBucketPolicyArgs.builder().bucket(bucketName).build());
            System.out.println(bucketPolicy);
        }catch (Exception e){
            log.error("错误:"+e.getMessage());
        }
    }


    /**
     * 判断文件是否存在
     * @param bucketName 存储桶
     * @param objectName 文件名
     * @return
     */
    public  Boolean isObjectExist(String bucketName, String objectName) {
        boolean exist = true;
        try {
            minioClient.statObject(StatObjectArgs.builder().bucket(bucketName).object(objectName).build());
        } catch (Exception e) {
            exist = false;
        }
        return exist;
    }

    /**
     * 判断文件夹是否存在
     *
     * @param bucketName 桶名称
     * @param folderName 文件夹名称
     * @return true存在, 反之
     */
    public Boolean checkFolderIsExist(String bucketName, String folderName) {
        try {
            Iterable<Result<Item>> results = minioClient.listObjects(
                    ListObjectsArgs
                            .builder()
                            .bucket(bucketName)
                            .prefix(folderName)
                            .recursive(false)
                            .build());
            for (Result<Item> result : results) {
                Item item = result.get();
                if (item.isDir() && folderName.equals(item.objectName())) {
                    return true;
                }
            }
        } catch (Exception e) {
            return false;
        }
        return true;
    }
}

文章来源:https://blog.csdn.net/xnian_/article/details/134923538
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。