SpringBoot框架:集成Minio完成图片上传

一、导入依赖

  在pom文件中引入Minio依赖:

 <!-- minio -->
 <dependency>
    <groupId>io.minio</groupId>
    <artifactId>minio</artifactId>
    <version>3.0.10</version>
 </dependency>

二、配置信息

  在yml配置文件中添加minio的地址、用户名、密码等信息:

minio:
  url: http://ip:port
  accessKey: username
  secretKey: password

三、接口编写

  新建一个minio相关操作接口的controller类,代码如下:

package com.dl.wall.controller;

import com.dl.wall.bean.ResultBean;
import io.minio.MinioClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

/**
 * minio相关接口
 */
@RestController
@RequestMapping("/File")
public class MinioController {

    /** 配置文件中获取minio各项值 */
    @Value("${minio.url}")
    private String url;
    @Value("${minio.accessKey}")
    private String accessKey;
    @Value("${minio.secretKey}")
    private String secretKey;

    /**
     * minio文件上传
     * @param file
     * @return
     * @throws Exception
     */
    @RequestMapping("/uploadFile")
    public ResultBean upload(@RequestParam("file") MultipartFile file) throws Exception {
        //初始化
        MinioClient minioClient = new MinioClient(url, accessKey, secretKey);
        //得到文件流
        InputStream is= file.getInputStream();
        //使用uuid生成新的唯一文件名
        String fileName = UUID.randomUUID().toString().replace("-","")+file.getOriginalFilename();
        //获取文件类型
        String contentType = file.getContentType();
        //把文件放置Minio桶
        minioClient.putObject("honorwall",fileName,is,contentType);
        //获取访问路径
        String url = minioClient.presignedGetObject("honorwall", fileName);
        if(url != null){
            //返回路径不为空,即上传文件成功
            return new ResultBean(ResultBean.SUCCESS,"文件上传成功",url.split("\?")[0]);
        }else{
            //上传失败
            return new ResultBean(ResultBean.FAIL,"文件上传失败",null);
        }
    }

}

四、接口测试

  使用postman对该接口进行调试,通过post进行传参。

  

  上传成功,返回的结果为图片的访问路径(改为永久可访问后的图片可通过路径直接查看):

  

原文地址:https://www.cnblogs.com/guobin-/p/14683980.html