前言

MInIO的安装有很多方法、单实例的、集群分布式的、docker部署的、支持k8s的,我们使用最简单的一种安装方式:linux单节点安装。

如果希望对MinIO有深入的掌握,访问MinIO官网:https://min.io


一、minio安装?

  1. 进入/opt目录创建minio文件夹

    	cd /opt
    	mkdir minio
    
  2. 下载安装包

    	wget https://dl.minio.io/server/minio/release/linux-amd64/minio
    
    

    在这里插入图片描述

  3. 进入minio文件夹创建log文件

    	cd /minio
    	touch minio.log
    
  4. 赋予minio文件执行权限

    	chmod 777 minio
    
  5. 修改用户名密码

    	vim /etc/profile
    

    在文件最后追加这几句

    # set minio environment
    export MINIO_ROOT_USER=user_minio           #用户名
    export MINIO_ROOT_PASSWORD=password_minio   #密码
    
    

    再用此命令生效配置

    	 source /etc/profile  
    
  6. 启动minio

    ./minio server /opt/minio/data --console-address ":33639" --address ":9000"
    
    

    –console-address “:33639” 固定端口号否则每次启动端口号都会变化
    此命令启动关闭连接后台就会关掉 所以我们要后台启动

  7. 后台启动minio

       nohup ./minio server /opt/minio/data --console-address ":33639" --address ":9000"
    

二、项目集成

1.引入依赖

    <dependency>
      <groupId>io.minio</groupId>
      <artifactId>minio</artifactId>
      <version>8.2.1</version>
    </dependency>

2.yaml配置

minio:
  endpoint: http://192.168.233.123:9000 #Minio服务所在地址
  accessKey: minioadmin                 #连接Minio用户名
  secretKey: minioadmin                 #连接Minio密码
  bucketName: testadmin                 #Minio数据桶名称

3.MinIoConfig.class 配置类

import io.minio.MinioClient;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
 
/**
 * @author: yujie.li
 * @description
 * @date 2023/7/18
 */
@Data
@Configuration
@ConfigurationProperties(prefix = "minio")
public class MinIoConfig {
 
    /**
     * 访问密钥
     */
    @Value("${minio.accessKey}")
    private String accessKey;
 
    /**
     * 密钥
     */
    @Value("${minio.secretKey}")
    private String secretKey;
 
    /**
     * 访问api Url
     */
    @Value("${minio.endpoint}")
    private String endpoint;
 
    /**
     * 捅名称
     */
    @Value("${minio.bucketName}")
    private String bucketName;
 
    /**
     * 创建MinIo客户端
     *
     * @return
     */
    @Bean
    public MinioClient minioClient() {
 
        return MinioClient.builder()
                .endpoint(endpoint)
                .credentials(accessKey, secretKey)
                .build();
    }
 
}

3.MinIOUtil .class 工具类

package com.casit.datafill.config;


import io.minio.GetObjectArgs;
import io.minio.GetPresignedObjectUrlArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.errors.*;
import io.minio.http.Method;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Component
public class MinioUtils {
    @Autowired
    private MinioClient minioClient;
    /**
     * 捅名称
     */
    @Value("${minio.bucketName}")
    private String bucketName;

    /**
     * putObject上传文件
     *
     * @param file 文件
     * @return filePath
     */
    public String putObject(MultipartFile file) throws IOException, ServerException, InsufficientDataException, InternalException, InvalidResponseException, InvalidKeyException, NoSuchAlgorithmException, XmlParserException, ErrorResponseException, InvalidKeyException {
        //文件名
        String originalFilename = file.getOriginalFilename();
        //文件流
        InputStream inputStream = file.getInputStream();
        //文件大小
        long size = file.getSize();
        //文件路径

        String filePath = UUID.randomUUID() + originalFilename;
        System.out.println(filePath+"\t文件路径");
        //存储方法 putObject
        minioClient.putObject(PutObjectArgs.builder()
                .bucket(bucketName)
                .object(filePath)
                .stream(inputStream, size, -1)
                .contentType(file.getContentType())
                .build());
        return filePath;
    }


    /**
     * 预览图片
     * @param fileName
     * @return
     */
    public String preview(String fileName){
        // 查看文件地址
        GetPresignedObjectUrlArgs build = new GetPresignedObjectUrlArgs().builder().bucket(bucketName).object(fileName).method(Method.GET).build();
        try {
            String url = minioClient.getPresignedObjectUrl(build);
            return url;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 下载文件
     *
     * @param filePath 文件路径
     */
    public void getObject(HttpServletResponse httpServletResponse, String filePath) throws IOException, InvalidKeyException, InvalidResponseException, InsufficientDataException, NoSuchAlgorithmException, ServerException, InternalException, XmlParserException, ErrorResponseException {
        String fileName = filePath;
        InputStream inputStream = minioClient.getObject(GetObjectArgs.builder()
                .bucket(bucketName)
                .object(filePath)
                .build());
        downloadFile(httpServletResponse, inputStream, fileName);
    }

    /**
     * 获取文件路径
     *
     * @param originalFilename 原始文件名称
     * @return FilePath
     */
    public String createFilePath(String originalFilename) {
        return new SimpleDateFormat("yyyy/MM/dd").format(new Date()) + "/" + originalFilename;
    }

    /**
     * 根据文件路径获取文件名称
     *
     * @param filePath 文件路径
     * @return 文件名
     */
    public String getFileName(String filePath) {
        String[] split = StringUtils.split(filePath, "/");
        return split[split.length - 1];
    }

    /**
     * 下载文件
     *
     * @param httpServletResponse httpServletResponse
     * @param inputStream         inputStream
     * @param fileName            文件名
     * @throws IOException IOException
     */
    public void downloadFile(HttpServletResponse httpServletResponse, InputStream inputStream, String fileName) throws IOException {
        //设置响应头信息,告诉前端浏览器下载文件
        httpServletResponse.setContentType("application/octet-stream;charset=UTF-8");
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
        //获取输出流进行写入数据
        OutputStream outputStream = httpServletResponse.getOutputStream();
        // 将输入流复制到输出流
        byte[] buffer = new byte[4096];
        int bytesRead = -1;
        while ((bytesRead = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, bytesRead);
        }
        // 关闭流资源
        inputStream.close();
        outputStream.close();
    }
}


4.接口Controller

package com.casit.datafill.controller;

import cn.interai.jeaf.common.beans.R;
import com.casit.datafill.config.MinioUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Api(tags = "文件管理")
@RestController
@RequestMapping("/datafill/file")
public class FileController {
    @Autowired
    private MinioUtils minioUtil;

    @PostMapping("/upload")
    @ApiOperation("文件上传")
    public R<String> upload(@RequestPart MultipartFile file) {
        String filePath;
        try {
            filePath = minioUtil.putObject(file);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("上传失败");
        }
        return R.success(filePath);
    }

    @GetMapping("/download")
    @ApiOperation("文件下载")
    public void download(HttpServletResponse response, @RequestParam(value = "filepath") String filepath) throws IOException {
        try {
            minioUtil.getObject(response, filepath);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @GetMapping("/preview")
    @ApiOperation("预览")
    public R<String> preview(@RequestParam(value = "filepath") String filepath)  {

        return R.success(minioUtil.preview(filepath));
    }

}

Logo

K8S/Kubernetes社区为您提供最前沿的新闻资讯和知识内容

更多推荐