1 MinIO核心概念
下面介绍MinIO中的几个核心概念,这些概念在所有的对象存储服务中也都是通用的。
-
对象(Object)
对象是实际的数据单元,例如我们上传的一个图片。
-
存储桶(Bucket)
存储桶是用于组织对象的命名空间,类似于文件夹。每个存储桶可以包含多个对象。
-
端点(Endpoint)
端点是MinIO服务器的网络地址,用于访问存储桶和对象,例如
http://192.168.10.101:9000
注意:
9000
为MinIO的API的默认端口,前边配置的9001
以为管理页面端口。 -
Access Key 和 Secret Key
Access Key是用于标识和验证访问者身份的唯一标识符,相当于用户名。
Secret Key 是与Access Key关联的密码,用于验证访问者的身份。
2.上传图片到minio当中去
-
创建一个Maven项目
-
引入如下依赖
XML<dependency> <groupId>io.minio</groupId> <artifactId>minio</artifactId> <version>8.5.3</version> </dependency>
-
编写如下内容
javapublic class App { public static void main(String[] args) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException { //1.创建 MinioClient对象 MinioClient minioClient = MinioClient.builder().credentials("minioadmin", "minioadmin").endpoint("http://192.168.153.128:9000").build(); //2.判断指定名称的桶是否存在 boolean flag = minioClient.bucketExists(BucketExistsArgs.builder().bucket("b002").build()); //3.如果不存在,则先创建桶并设置策略 if (!flag) { //创建桶 minioClient.makeBucket(MakeBucketArgs.builder().bucket("b002").build()); //指定策略 String policy = """ { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "AWS": [ "*" ] }, "Action": [ "s3:GetObject" ], "Resource": [ "arn:aws:s3:::b002/*" ] } ] } """; minioClient.setBucketPolicy(SetBucketPolicyArgs.builder() .bucket("b002") .config(policy).build()); } // 4.上传图片 minioClient.uploadObject(UploadObjectArgs.builder() .bucket("b002") .object("公寓-健身房.jpg") .filename("C:\\Users\\codercui\\Pictures\\7.images\\房间-厨房-2.jpg") .build()); } }
-
运行测试
运行上述代码,然后查看MinIO管理页面,观察是否上传成功。
项目当中实现真正的图片上传
1. 图片上传流程
可以看出图片上传接口接收的是图片文件,返回的Minio对象的URL。
2. 图片上传接口开发
配置Minio Client
1.引入Minio Maven依赖
-
在common模块 的
pom.xml
文件增加如下内容:XML<dependency> <groupId>io.minio</groupId> <artifactId>minio</artifactId> </dependency>
2.配置Minio相关参数
在application.yml
中配置Minio的endpoint
、accessKey
、secretKey
、bucketName
等参数
XML
minio:
endpoint: http://<hostname>:<port>
access-key: <access-key>
secret-key: <secret-key>
bucket-name: <bucket-name>
注意 :上述<hostname>
、<port>
等信息需根据实际情况进行修改。
3.创建一个minio的配置类
在common模块 中创建com.atguigu.lease.common.minio.MinioProperties
,内容如下
java
package com.cuihub.lease.common.minio;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties(prefix = "minio")
@Data
public class MinioProperties {
private String endpoint;
private String accessKey;
private String secretKey;
private String bucketName;
}
@ConfigurationProperties 需要的依赖添加到pom.xml当中去
XML
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
4.创建MinioConfiguration
在common模块 中创建com.atguigu.lease.common.minio.MinioConfiguration
,内容如下
java
package com.cuihub.lease.common.minio;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.SetBucketPolicyArgs;
import io.minio.errors.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
@Configuration
@EnableConfigurationProperties(MinioProperties.class)
public class MinioConfiguration {
@Autowired
private MinioProperties minioProperties;
@Bean
public MinioClient minioClient() throws ServerException, InsufficientDataException,
ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException,
InvalidResponseException, XmlParserException, InternalException {
MinioClient minioClient = MinioClient.builder()
.endpoint(minioProperties.getEndpoint())
.credentials(minioProperties.getAccessKey(), minioProperties.getAccessKey())
.build();
boolean bucketExistsFlag = minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioProperties.getBucketName()).build());
if (!bucketExistsFlag){
minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioProperties.getBucketName()).build());
String policy = """
{
"Statement" : [ {
"Action" : "s3:GetObject",
"Effect" : "Allow",
"Principal" : "*",
"Resource" : "arn:aws:s3:::%s/*"
} ],
"Version" : "2012-10-17"
}
""".formatted(minioProperties.getBucketName());
minioClient.setBucketPolicy(SetBucketPolicyArgs.builder().config(policy).bucket(minioProperties.getBucketName()).build());
}
return minioClient;
}
}
5. 创建一个控制类
java
package com.cuihub.lease.web.admin.controller.apartment;
import com.cuihub.lease.common.result.Result;
import com.cuihub.lease.web.admin.service.FileService;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.errors.*;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.io.StringReader;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
@Tag(name = "文件管理")
@RequestMapping("/admin/file")
@RestController
public class FileUploadController {
@Autowired
private FileService fileService;
@Operation(summary = "上传文件")
@CrossOrigin
@PostMapping("upload")
public Result<String> upload(@RequestParam MultipartFile file) throws Exception {
String url = fileService.upload(file);
// System.out.println("url = " + url);
return Result.ok(url);
}
}
6.创建FileService业务逻辑层
java
package com.cuihub.lease.web.admin.service;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
public interface FileService {
String upload(MultipartFile multipartFile) throws Exception;
}
7.创建一个j接口实现类imp
java
package com.cuihub.lease.web.admin.service.impl;
import com.cuihub.lease.common.minio.MinioProperties;
import com.cuihub.lease.web.admin.service.FileService;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
@Service
public class FileServiceImpl implements FileService {
@Autowired
private MinioProperties minioProperties;
@Autowired
private MinioClient minioClient;
@Override
public String upload(MultipartFile file) throws Exception {
//获取原始文件名
String originalFilename = file.getOriginalFilename();
//创建新的文件名
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
originalFilename= sdf.format(new Date())+ "/" +( UUID.randomUUID().toString().replaceAll("-", ""))+"_"+originalFilename;
minioClient.putObject(PutObjectArgs.builder().
stream(file.getInputStream(), file.getSize(), -1)
.contentType(file.getContentType())
.bucket(minioProperties.getBucketName())
.object(originalFilename)
.build());
System.out.println(minioProperties.getEndpoint()+minioProperties.getBucketName()+"fashedkjhgft");
String url = String.format("%s/%s",minioProperties.getEndpoint(),minioProperties.getBucketName())+"/"+originalFilename;
return url;
}
}
这时候你就可以给前端返回一个图片的url地址啦
注意:
1.添加配置文件指定桶名
2.String.format 当中的占位符是%s,这里的s是小写,如果是大写%S那么返回的地址里面的字母全是大写的了