一、理解
MinIO 是一个基于Apache License v2.0开源协议的对象存储服务 。它兼容亚马逊S3云存储服务接口,非常适合于存储大容量非结构化的数据,例如图片、视频、日志文件、备份数据和容器/虚拟机镜像等,而一个对象文件可以是任意大小,从几kb到最大5T不等。
MinIO是一个非常轻量的服务,可以很简单的和其他应用的结合,类似 NodeJS, Redis 或者 MySQL。 支持分布式 ,上传的数据是在自己的云服务器上 。
二、下载
其他下载方式可以看官网http://docs.minio.org.cn/docs/
docker下载安装
docker pull minio/minio
docker run -d -p 9000:9000 -p 9090:9090 --name=minio
--restart=always
-e "MINIO_ROOT_USER=admin"
-e "MINIO_ROOT_PASSWORD=admin123456"
-v /home/minio/data:/data
-v /home/minio/config:/root/.minio
minio/minio server /data
--console-address ":9000" --address ":9090"
1、不加–console-address “:9000” --address ":9090"会导致端口一直变,页面访问不了 2、密码不低于8位 访问 http//:ip:9000 账号密码是你设置的
新建个桶,文件存在桶里
docker logs 容器id 查看日志 代码api连接的地址是ip:9090
三、整合springboot
1、配置
pom依赖
<dependency>
<groupId>io.minio</groupId>
<artifactId>minio</artifactId>
<version>8.2.1</version>
</dependency>
yml配置
server:
port: 7777
minio:
minio_url: 你的ip:9090
minio_name: admin
minio_pass: admin123456
bucketName: test
新建配置类
@Configuration
public class MinIoClientConfig {
@Value(value = "${minio.minio_url}")
private String minioUrl;
@Value(value = "${minio.minio_name}")
private String minioName;
@Value(value = "${minio.minio_pass}")
private String minioPass;
@Value(value = "${minio.bucketName}")
private String bucketName;
@Bean
public void initMinio(){
if(!minioUrl.startsWith("http")){
minioUrl = "http://" + minioUrl;
}
if(!minioUrl.endsWith("/")){
minioUrl = minioUrl.concat("/");
}
MinioUtil.setMinioUrl(minioUrl);
MinioUtil.setMinioName(minioName);
MinioUtil.setMinioPass(minioPass);
MinioUtil.setBucketName(bucketName);
}
2、工具类
文件过滤类(给minio上传用) 判断类型等,主要做一些限制
package com.example.minio.util;
import org.springframework.web.multipart.MultipartFile;
import org.apache.commons.lang3.StringUtils;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
public class FileFilterUtil {
private static String[] forbidType = {"jsp","php"};
final static HashMap<String, String> fileTypeMap = new HashMap<>();
static {
fileTypeMap.put("3c25402070616765206c", "jsp");
fileTypeMap.put("3c3f7068700a0a2f2a2a0a202a205048", "php");
}
private static String getFileTypeBySuffix(String fileName) {
return fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
}
public static void fileTypeFilter(MultipartFile file) throws Exception {
String suffix = getFileType(file);
for (String type : forbidType) {
if (type.contains(suffix)) {
throw new Exception("上传失败,文件类型异常:" + suffix);
}
}
}
private static String getFileType(MultipartFile file) throws Exception {
String fileExtendName = null;
InputStream is;
try {
is = file.getInputStream();
byte[] b = new byte[10];
is.read(b, 0, b.length);
String fileTypeHex = String.valueOf(bytesToHexString(b));
Iterator<String> keyIter = fileTypeMap.keySet().iterator();
while (keyIter.hasNext()) {
String key = keyIter.next();
if (key.toLowerCase().startsWith(fileTypeHex.toLowerCase().substring(0, 5))
|| fileTypeHex.toLowerCase().substring(0, 5).startsWith(key.toLowerCase())) {
fileExtendName = fileTypeMap.get(key);
break;
}
}
if (StringUtils.isBlank(fileExtendName)) {
String fileName = file.getOriginalFilename();
return getFileTypeBySuffix(fileName);
}
is.close();
return fileExtendName;
} catch (Exception exception) {
throw new Exception(exception.getMessage(), exception);
}
}
private static String bytesToHexString(byte[] src) {
StringBuilder stringBuilder = new StringBuilder();
if (src == null || src.length <= 0) {
return null;
}
for (int i = 0; i < src.length; i++) {
int v = src[i] & 0xFF;
String hv = Integer.toHexString(v);
if (hv.length() < 2) {
stringBuilder.append(0);
}
stringBuilder.append(hv);
}
return stringBuilder.toString();
}
public static String filter(String str) throws PatternSyntaxException {
String regEx = "[`_《》~!@#$%^&*()+=|{}':;',\\[\\].<>?~!@#¥%……&*()——+|{}【】‘;:”“’。,、?]";
Pattern p = Pattern.compile(regEx);
Matcher m = p.matcher(str);
return m.replaceAll("").trim();
}
public static String getFileName(String fileName){
int unixSep = fileName.lastIndexOf('/');
int winSep = fileName.lastIndexOf('\\');
int pos = (winSep > unixSep ? winSep : unixSep);
if (pos != -1) {
fileName = fileName.substring(pos + 1);
}
fileName = fileName.replace("=","").replace(",","").replace("&","")
.replace("#", "").replace("“", "").replace("”", "");
fileName=fileName.replaceAll("\\s","");
return fileName;
}
}
MInio工具类 静态工具类
package com.example.minio.util;
import io.minio.*;
import io.minio.http.Method;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;
import java.io.InputStream;
import java.net.URLDecoder;
@Slf4j
public class MinioUtil {
private static String minioUrl;
private static String minioName;
private static String minioPass;
private static String bucketName;
public static void setMinioUrl(String minioUrl) {
MinioUtil.minioUrl = minioUrl;
}
public static void setMinioName(String minioName) {
MinioUtil.minioName = minioName;
}
public static void setMinioPass(String minioPass) {
MinioUtil.minioPass = minioPass;
}
public static void setBucketName(String bucketName) {
MinioUtil.bucketName = bucketName;
}
public static String getMinioUrl() {
return minioUrl;
}
public static String getBucketName() {
return bucketName;
}
private static MinioClient minioClient = null;
public static String upload(MultipartFile file, String bizPath, String customBucket) {
String file_url = "";
bizPath= FileFilterUtil.filter(bizPath);
String newBucket = bucketName;
if(ObjectUtils.isNotEmpty(customBucket)){
newBucket = customBucket;
}
try {
initMinio(minioUrl, minioName,minioPass);
if(minioClient.bucketExists(BucketExistsArgs.builder().bucket(newBucket).build())) {
log.info("Bucket already exists.");
} else {
minioClient.makeBucket(MakeBucketArgs.builder().bucket(newBucket).build());
log.info("create a new bucket.");
}
FileFilterUtil.fileTypeFilter(file);
InputStream stream = file.getInputStream();
String orgName = file.getOriginalFilename();
if("".equals(orgName)){
orgName=file.getName();
}
orgName = FileFilterUtil.getFileName(orgName);
String objectName = bizPath+"/"
+( orgName.indexOf(".")==-1
?orgName + "_" + System.currentTimeMillis()
:orgName.substring(0, orgName.lastIndexOf(".")) + "_" + System.currentTimeMillis() + orgName.substring(orgName.lastIndexOf("."))
);
if(objectName.startsWith("/")){
objectName = objectName.substring(1);
}
PutObjectArgs objectArgs = PutObjectArgs.builder().object(objectName)
.bucket(newBucket)
.contentType("application/octet-stream")
.stream(stream,stream.available(),-1).build();
minioClient.putObject(objectArgs);
stream.close();
file_url = minioUrl+newBucket+"/"+objectName;
}catch (Exception e){
log.error(e.getMessage(), e);
}
return file_url;
}
public static String upload(MultipartFile file, String bizPath) {
return upload(file,bizPath,null);
}
public static InputStream getMinioFile(String bucketName,String objectName){
InputStream inputStream = null;
try {
initMinio(minioUrl, minioName, minioPass);
GetObjectArgs objectArgs = GetObjectArgs.builder().object(objectName)
.bucket(bucketName).build();
inputStream = minioClient.getObject(objectArgs);
} catch (Exception e) {
log.info("文件获取失败" + e.getMessage());
}
return inputStream;
}
public static void removeObject(String bucketName, String objectName) {
try {
initMinio(minioUrl, minioName,minioPass);
RemoveObjectArgs objectArgs = RemoveObjectArgs.builder().object(objectName)
.bucket(bucketName).build();
minioClient.removeObject(objectArgs);
}catch (Exception e){
log.info("文件删除失败" + e.getMessage());
}
}
public static String getObjectURL(String bucketName, String objectName, Integer expires) {
initMinio(minioUrl, minioName,minioPass);
try{
GetPresignedObjectUrlArgs objectArgs = GetPresignedObjectUrlArgs.builder().object(objectName)
.bucket(bucketName)
.expiry(expires).method(Method.GET).build();
String url = minioClient.getPresignedObjectUrl(objectArgs);
return URLDecoder.decode(url,"UTF-8");
}catch (Exception e){
log.info("文件路径获取失败" + e.getMessage());
}
return null;
}
private static MinioClient initMinio(String minioUrl, String minioName,String minioPass) {
if (minioClient == null) {
try {
minioClient = MinioClient.builder()
.endpoint(minioUrl)
.credentials(minioName, minioPass)
.build();
} catch (Exception e) {
e.printStackTrace();
}
}
return minioClient;
}
public static String upload(InputStream stream,String relativePath) throws Exception {
initMinio(minioUrl, minioName,minioPass);
if(minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build())) {
log.info("Bucket already exists.");
} else {
minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
log.info("create a new bucket.");
}
PutObjectArgs objectArgs = PutObjectArgs.builder().object(relativePath)
.bucket(bucketName)
.contentType("application/octet-stream")
.stream(stream,stream.available(),-1).build();
minioClient.putObject(objectArgs);
stream.close();
return minioUrl+bucketName+"/"+relativePath;
}
}
3、测试
@RestController
public class testController {
@PostMapping("/upload")
public void upload(MultipartFile file){
MinioUtil.upload(file,"/image","test");
}
@GetMapping("/getFile")
public void getFile(String bucketName, String objectName, HttpServletResponse httpResponse) throws IOException {
InputStream minioFile = MinioUtil.getMinioFile(bucketName, objectName);
byte buf[] = new byte[1024];
int length = 0;
httpResponse.reset();
httpResponse.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(objectName, "UTF-8"));
httpResponse.setContentType("application/octet-stream");
httpResponse.setCharacterEncoding("utf-8");
OutputStream outputStream = httpResponse.getOutputStream();
while ((length = minioFile.read(buf)) > 0) {
outputStream.write(buf, 0, length);
}
outputStream.close();
}
@GetMapping("/removeFile")
public void removeFile(String bucketName,String objectName){
MinioUtil.removeObject(bucketName,objectName);
}
@GetMapping("/getObjectURL")
public void getObjectURL(String bucketName,String objectName){
String objectURL = MinioUtil.getObjectURL(bucketName, objectName, 100);
System.out.println("objectURL = " + objectURL);
}
}
git地址:https://gitee.com/hmb000/minio.git
|