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進行傳參。

  

  上傳成功,返回的結果為圖片的訪問路徑(改為永久可訪問后的圖片可通過路徑直接查看):

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM