MinIO上传

MinIO上传

docker 搭建minio

yml 复制代码
version: '3'

services:
  minio:
    image: minio/minio:RELEASE.2023-04-13T03-08-07Z
    container_name: minio
    ports:
      # api 端口
      - "9000:9000"
      # 控制台端口
      - "9001:9001"
    environment:
      # 时区上海
      TZ: Asia/Shanghai
      # 管理后台用户名
      MINIO_ROOT_USER: root
      # 管理后台密码,最小8个字符
      MINIO_ROOT_PASSWORD: root123456
      # https需要指定域名
      #MINIO_SERVER_URL: "https://xxx.com:9000"
      #MINIO_BROWSER_REDIRECT_URL: "https://xxx.com:9001"
      # 开启压缩 on 开启 off 关闭
      MINIO_COMPRESS: "off"
      # 扩展名 .pdf,.doc 为空 所有类型均压缩
      MINIO_COMPRESS_EXTENSIONS: ""
      # mime 类型 application/pdf 为空 所有类型均压缩
      MINIO_COMPRESS_MIME_TYPES: ""
    volumes:
      # 映射当前目录下的data目录至容器内/data目录
      - /www/docker/minio/data:/data
      # 映射配置目录
      - /www/docker/minio/config:/root/.minio/
    command: server --address ':9000' --console-address ':9001' /data  # 指定容器中的目录 /data
    privileged: true
    network_mode: "host"

xml配置文件

xml 复制代码
	<dependency>
		<groupId>io.minio</groupId>
		<artifactId>minio</artifactId>
		<version>8.5.10</version>
	</dependency>

yml配置文件

yml 复制代码
minio:
  endpoint: http://192.168.165.187:9000
  accessKey: 5UldcOke8mfManPN
  secretKey: xtMnHkrJR2SxAhACpubd5sya4uwV7LF5
  bucket: wzfile
  readPath: http://192.168.165.187:9000

获取yml配置参数

java 复制代码
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.io.Serializable;
@Data
@Component
@ConfigurationProperties(prefix = "minio")
public class MinIOConfigProperties implements Serializable {
    private String accessKey;
    private String secretKey;
    private String bucket;
    private String endpoint;
    private String readPath;

}

minio 配置

java 复制代码
import io.minio.MinioClient;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Data
@Configuration
@RequiredArgsConstructor
@EnableConfigurationProperties({MinIOConfigProperties.class})
public class MinIOConfig {
    private final MinIOConfigProperties minIOConfigProperties;

    @Bean
    public MinioClient buildMinioClient() {
        return MinioClient
                .builder()
                .credentials(minIOConfigProperties.getAccessKey(), minIOConfigProperties.getSecretKey())
                .endpoint(minIOConfigProperties.getEndpoint())
                .build();
    }

}

上传服务类

java 复制代码
import cn.hutool.core.util.ObjectUtil;
import io.minio.MinioClient;
import io.minio.ObjectWriteResponse;
import io.minio.PutObjectArgs;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

@Service
@Slf4j
@RequiredArgsConstructor
public class FileServiceImpl implements IFileService {

    private final MinioClient minioClient;
    private final MinIOConfigProperties minIOConfigProperties;

    @Override
    public String uploadFileToCloud(MultipartFile file) {
        if (ObjectUtil.isNull(file)){
            log.error("上传文件为空");
            throw new ApiException(ResultCode.ERROR,"上传文件为空");
        }

        try{

            String fileName = file.getOriginalFilename();
            InputStream inputStream = file.getInputStream();
            // 获取当前日期
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
            String datePath = sdf.format(new Date());
            // 组合存储对象名称

            String objectName = datePath + "/" + generateFileNameWithRandom(fileName);
            log.info("文件上传开始;{}",objectName);
            minioClient.putObject(PutObjectArgs.builder()
                    .bucket(minIOConfigProperties.getBucket())
                    .object(objectName)
                    .stream(inputStream, inputStream.available(), -1)
                    .build());

            FileBo fileBo = new FileBo();
          
            String url = minIOConfigProperties.getEndpoint()+"/"+minIOConfigProperties.getBucket()+"/"+objectName;

            return url ;
        }catch (Exception e){
            throw new ApiException(ResultCode.ERROR,e.getMessage());
        }

    }

    /**
     * 获取文件名
     * @param fileName
     * @return
     */
    @Override
    public String getFileName(String fileName) {

        int lastIndex = fileName.lastIndexOf('.');
        if (lastIndex!= -1) {
            return fileName.substring(0, lastIndex);
        }
        return null;
    }

    /**
     * 获取文件后缀
     * @param fileName
     * @return
     */
    @Override
    public String getFileSuffix(String fileName) {
        if (fileName == null) {
            return "";
        }
        int lastIndex = fileName.lastIndexOf('.');
        if (lastIndex == -1) {
            return "";
        }
        return fileName.substring(lastIndex);
    }




    private String generateFileNameWithRandom(String originalFileName) {
        String baseName = originalFileName;
        int lastIndex = originalFileName.lastIndexOf('.');
        if (lastIndex!= -1) {
            baseName = originalFileName.substring(0, lastIndex);
        }
        String randomPart = generateRandomPart();
        String fileExtension = "";
        if (lastIndex!= -1) {
            fileExtension = originalFileName.substring(lastIndex);
        }
        return baseName + randomPart + fileExtension;
    }

    private String generateRandomPart() {
        Random random = new Random();
        int randomNumber = random.nextInt(9000) + 1000;
        return "_" + randomNumber;
    }
}
相关推荐
苏-言1 小时前
SSM框架探秘:Spring 整合 Mybatis 框架
java·spring·mybatis
qq_447663051 小时前
java-----多线程
java·开发语言
a辰龙a1 小时前
【Java报错解决】警告: 源发行版 11 需要目标发行版 11
java·开发语言
听海边涛声1 小时前
JDK长期支持版本(LTS)
java·开发语言
IpdataCloud1 小时前
Java 获取本机 IP 地址的方法
java·开发语言·tcp/ip
MyMyMing1 小时前
Java的输入和输出
java·开发语言
忆~遂愿1 小时前
3大关键点教你用Java和Spring Boot快速构建微服务架构:从零开发到高效服务注册与发现的逆袭之路
java·人工智能·spring boot·深度学习·机器学习·spring cloud·eureka
云夏之末1 小时前
【Java报错已解决】java.lang.UnsatisfiedLinkError
java·开发语言
计算机-秋大田3 小时前
基于SpringBoot的假期周边游平台的设计与实现(源码+SQL脚本+LW+部署讲解等)
java·vue.js·spring boot·后端·课程设计
麻辣香蝈蝈3 小时前
【Java】微服务找不到问题记录can not find user-service
java·微服务·nacos