SpringBoot集成MinIO的示例代碼
簡介
對象存儲服務(wù)OSS(Object Storage Service)是一種海量、安全、低成本、高可靠的云存儲服務(wù),適合存放任意類型的文件。容量和處理能力彈性擴展,多種存儲類型供選擇,全面優(yōu)化存儲成本。今天我這里主要講解SpringBoot如何集成MinIO。
引入依賴
<dependency>
<groupId>io.minio</groupId>
<artifactId>minio</artifactId>
<version>7.0.2</version>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>3.14.9</version>
<scope>compile</scope>
</dependency>yml文件配置
# Tomcat
server:
port: 9100
# 自定義配置項,方便在代碼中使用
minio:
endpoint: 127.0.0.1
port: 9001
accessKey: minioadmin
secretKey: minioadmin
bucketName: upload
spring:
servlet:
multipart:
max-file-size: 10000MB
max-request-size: 20000MB編寫配置類
package com.example.mimio.config;
import io.minio.MinioClient;
import io.minio.errors.InvalidEndpointException;
import io.minio.errors.InvalidPortException;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Data
@Configuration
/*加載yml文件中以minio開頭的配置項*/
@ConfigurationProperties(prefix = "minio")
public class MinioConfig {
/*會自動的對應(yīng)配置項中對應(yīng)的key*/
private String endpoint;//minio.endpoint
private String accessKey;
private String secretKey;
private Integer port;
/*把官方提供的MinioClient客戶端注冊到IOC容器中*/
@Bean
public MinioClient getMinioClient() throws InvalidPortException, InvalidEndpointException {
MinioClient minioClient = new MinioClient(getEndpoint(), getPort(), getAccessKey(), getSecretKey(), false);
return minioClient;
}
}編寫工具類
package com.example.mimio.util;
import io.minio.MinioClient;
import io.minio.ObjectStat;
import io.minio.PutObjectOptions;
import io.minio.Result;
import io.minio.errors.*;
import io.minio.messages.DeleteError;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
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.util.ArrayList;
import java.util.List;
@Component
public class MinioClientUtil {
@Value("${minio.bucketName}")
private String bucketName;
@Resource
private MinioClient minioClient;
private static final int DEFAULT_EXPIRY_TIME = 7 * 24 * 3600;
/**
* 檢查存儲桶是否存在
*/
public boolean bucketExists(String bucketName) throws InvalidKeyException, ErrorResponseException,
IllegalArgumentException, InsufficientDataException, InternalException, InvalidBucketNameException,
InvalidResponseException, NoSuchAlgorithmException, XmlParserException, IOException {
boolean flag = minioClient.bucketExists(this.bucketName);
if (flag) return true;
return false;
}
/**
* 通過InputStream上傳對象
*
* @param objectName 存儲桶里的對象名稱
* @param stream 要上傳的流 (文件的流)
*/
public boolean putObject(String objectName, InputStream stream) throws Exception {
//判斷 桶是否存在
boolean flag = bucketExists(bucketName);
if (flag) {
//往桶中添加數(shù)據(jù) minioClient 進行添加
/**
* 參數(shù)1: 桶的名稱
* 參數(shù)2: 文件的名稱
* 參數(shù)3: 文件的流
* 參數(shù)4: 添加的配置
*/
minioClient.putObject(bucketName, objectName, stream, new PutObjectOptions(stream.available(), -1));
ObjectStat statObject = statObject(objectName);
if (statObject != null && statObject.length() > 0) {
return true;
}
}
return false;
}
/**
* 刪除一個對象
* @param objectName 存儲桶里的對象名稱
*/
public boolean removeObject(String objectName)throws Exception {
boolean flag = bucketExists(bucketName);
if (flag) {
minioClient.removeObject(bucketName, objectName);
return true;
}
return false;
}
/**
* 刪除指定桶的多個文件對象,返回刪除錯誤的對象列表,全部刪除成功,返回空列表
* @param objectNames 含有要刪除的多個object名稱的迭代器對象
*/
public List<String> removeObject(List<String> objectNames) throws Exception {
List<String> deleteErrorNames = new ArrayList<>();
boolean flag = bucketExists(bucketName);
if (flag) {
Iterable<Result<DeleteError>> results = minioClient.removeObjects(bucketName, objectNames);
for (Result<DeleteError> result : results) {
DeleteError error = result.get();
deleteErrorNames.add(error.objectName());
}
}
return deleteErrorNames;
}
/**
* 獲取對象的元數(shù)據(jù)
* @param objectName 存儲桶里的對象名稱
*/
public ObjectStat statObject(String objectName) throws Exception {
boolean flag = bucketExists(bucketName);
if (flag) {
ObjectStat statObject = minioClient.statObject(bucketName, objectName);
return statObject;
}
return null;
}
/**
* 文件訪問路徑
* @param objectName 存儲桶里的對象名稱
*/
public String getObjectUrl(String objectName) throws Exception {
boolean flag = bucketExists(bucketName);
String url = "";
if (flag) {
url = minioClient.getObjectUrl(bucketName, objectName);
}
return url;
}
public void getObject(String filename, HttpServletResponse response){
InputStream in = null;
OutputStream out = null;
try{
in=minioClient.getObject(bucketName,filename);
int length=0;
byte[] buffer = new byte[1024];
out = response.getOutputStream();
response.reset();
response.addHeader("Content-Disposition",
" attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
response.setContentType("application/octet-stream");
while ((length = in.read(buffer)) > 0) {
out.write(buffer, 0, length);
}
}catch (Exception e){
e.printStackTrace();
}finally {
if (in != null){
try {
in.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
編寫控制器
package com.example.mimio.controller;
import com.example.mimio.response.ResponseData;
import com.example.mimio.util.MinioClientUtil;
import io.minio.errors.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;
@RestController
public class TestController {
@Autowired
public void setMinioClientUtil(MinioClientUtil minioClientUtil) {
this.minioClientUtil = minioClientUtil;
}
private MinioClientUtil minioClientUtil;
@PostMapping("/upload")
public ResponseData uploadMinio(@RequestPart MultipartFile file) throws Exception {
//拿到圖片 MultipartFile封裝接受的類
//拿到圖片的名稱
String filename = file.getOriginalFilename();
//拿到圖片的 UUId + 圖片類型 (解決圖片重名的問題 )
String uuid = UUID.randomUUID().toString();
String imgType = filename.substring(filename.lastIndexOf("."));
//圖片文件的新名稱 xxx/uuid.jpg 圖片拼接后的名
String fileName = uuid + imgType;
boolean flag = minioClientUtil.putObject(fileName, file.getInputStream());
String path = "/upload/" + fileName;
return flag ? ResponseData.success("上傳成功",path):ResponseData.failed("上傳失敗");
}
@PostMapping("/downLoad")
public ResponseData downLoadMinio(String url,HttpServletResponse response) throws Exception {
// String objectUrl = minioClientUtil.getObjectUrl("a9e203f9-1bbb-4d59-8c28-3a183c064502.sql")
String trim = url.trim();
String path = trim.substring(trim.indexOf("/", 1), trim.length());
minioClientUtil.getObject(path,response);
return null;
}
}上傳接口調(diào)用

下載接口調(diào)用

到此這篇關(guān)于SpringBoot集成MinIO的文章就介紹到這了,更多相關(guān)SpringBoot集成MinIO內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
InputStreamReader 和FileReader的區(qū)別及InputStream和Reader的區(qū)別
這篇文章主要介紹了InputStreamReader 和FileReader的區(qū)別及InputStream和Reader的區(qū)別的相關(guān)資料,需要的朋友可以參考下2015-12-12
java中的Io(input與output)操作總結(jié)(二)
這一節(jié)我們來討論關(guān)于文件自身的操作包括:創(chuàng)建文件對象、創(chuàng)建和刪除文件、文件的判斷和測試、創(chuàng)建目錄、獲取文件信息、列出文件系統(tǒng)的根目錄、列出目錄下的所有文件,等等,感興趣的朋友可以了解下2013-01-01
Springmvc請求參數(shù)類型轉(zhuǎn)換器及原生api代碼實例
這篇文章主要介紹了Springmvc請求參數(shù)類型轉(zhuǎn)換器及原生api代碼實例,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-10-10
SpringBoot Freemarker基礎(chǔ)配置與使用方式
文章主要介紹了在Spring Boot項目中使用FreeMarker模板引擎的基礎(chǔ)配置、使用方法和注意事項,包括依賴引入、配置文件設(shè)置、數(shù)據(jù)類型調(diào)用、運算符支持、時間格式轉(zhuǎn)換、邏輯表達式等2026-05-05
Java對象轉(zhuǎn)Json,關(guān)于@JSONField對象字段重命名和順序問題
這篇文章主要介紹了Java對象轉(zhuǎn)Json,關(guān)于@JSONField對象字段重命名和順序問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-08-08
springboot打成jar后獲取classpath下文件失敗的解決方案
這篇文章主要介紹了使用springboot打成jar后獲取classpath下文件失敗的解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-08-08
Java ==,equals()與hashcode()的使用
本文主要介紹了Java ==,equals()與hashcode()的使用,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-05-05

