赞
踩
依赖
- <!-- MinIO -->
- <dependency>
- <groupId>io.minio</groupId>
- <artifactId>minio</artifactId>
- <version>8.2.2</version>
- </dependency>
配置文件
- minio:
- endpoint: http://118.31.31.1
- port: 19000
- accessKey: admin1
- secretKey: 123456783
- bucketName: sif31an1
Minio配置类
-
- import io.minio.MinioClient;
- import lombok.Data;
- import org.springframework.boot.context.properties.ConfigurationProperties;
- import org.springframework.context.annotation.Bean;
- import org.springframework.context.annotation.Configuration;
-
- @Configuration
- @ConfigurationProperties(prefix = "minio")
- @Data
- public class MinioConfig {
-
- private String endpoint;
-
- private Integer port;
-
- private String bucketName;
-
- private String accessKey;
-
- private String secretKey;
-
- @Bean
- public MinioClient minioClient() {
- return MinioClient.builder().endpoint(endpoint, port, false).credentials(accessKey, secretKey).build();
- }
- }
Minio工具类
-
- import io.minio.*;
- import io.minio.http.Method;
- import io.minio.messages.Bucket;
- import io.minio.messages.DeleteObject;
- import io.minio.messages.Item;
- import lombok.extern.slf4j.Slf4j;
- import org.springframework.beans.factory.annotation.Value;
- import org.springframework.stereotype.Component;
- import org.springframework.web.multipart.MultipartFile;
-
- import javax.annotation.Resource;
- import java.io.ByteArrayInputStream;
- import java.io.InputStream;
- import java.io.UnsupportedEncodingException;
- import java.net.URLDecoder;
- import java.util.ArrayList;
- import java.util.LinkedList;
- import java.util.List;
- import java.util.Optional;
-
- /**
- * MinIO工具类
- *
- * @author guoj
- * @date 2021/12/14 19:30
- */
- @Slf4j
- @Component
- public class MinIOUtils {
-
- @Resource
- private MinioClient minioClient;
-
- @Value("${minio.endpoint}")
- private String endpoint;
- @Value("${minio.bucketName}")
- private String bucketName;
- @Value("${minio.accessKey}")
- private String accessKey;
- @Value("${minio.secretKey}")
- private String secretKey;
-
- private Integer imgSize = 100 * 1024 * 1024; //100M
-
- private Integer fileSize = 1 * 1024 * 1024 * 1024; //1G
-
-
- /**
- * 获取上传文件前缀路径
- *
- * @return
- */
- public String getBasisUrl() {
- return endpoint + "-" + bucketName + "-";
- }
-
- /****************************** Operate Bucket Start ******************************/
-
- /**
- * 启动SpringBoot容器的时候初始化Bucket
- * 如果没有Bucket则创建
- *
- * @throws Exception
- */
- public void createBucket(String bucketName) throws Exception {
- if (!bucketExists(bucketName)) {
- minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
- }
- }
-
- /**
- * 判断Bucket是否存在,true:存在,false:不存在
- *
- * @return
- * @throws Exception
- */
- public boolean bucketExists(String bucketName) throws Exception {
- return minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
- }
-
-
- /**
- * 获得Bucket的策略
- *
- * @param bucketName
- * @return
- * @throws Exception
- */
- public String getBucketPolicy(String bucketName) throws Exception {
- return minioClient
- .getBucketPolicy(
- GetBucketPolicyArgs
- .builder()
- .bucket(bucketName)
- .build()
- );
- }
-
-
- /**
- * 获得所有Bucket列表
- *
- * @return
- * @throws Exception
- */
- public List<Bucket> getAllBuckets() throws Exception {
- return minioClient.listBuckets();
- }
-
- /**
- * 根据bucketName获取其相关信息
- *
- * @param bucketName
- * @return
- * @throws Exception
- */
- public Optional<Bucket> getBucket(String bucketName) throws Exception {
- return getAllBuckets().stream().filter(b -> b.name().equals(bucketName)).findFirst();
- }
-
- /**
- * 根据bucketName删除Bucket,true:删除成功; false:删除失败,文件或已不存在
- *
- * @param bucketName
- * @throws Exception
- */
- public void removeBucket(String bucketName) throws Exception {
- minioClient.removeBucket(RemoveBucketArgs.builder().bucket(bucketName).build());
- }
-
- /****************************** Operate Bucket End ******************************/
-
-
- /****************************** Operate Files Start ******************************/
-
- /**
- * 判断文件是否存在
- *
- * @param bucketName 存储桶
- * @param objectName 文件名
- * @return
- */
- public boolean isObjectExist(String bucketName, String objectName) {
- boolean exist = true;
- try {
- minioClient.statObject(StatObjectArgs.builder().bucket(bucketName).object(objectName).build());
- } catch (Exception e) {
- log.error("[Minio工具类]>>>> 判断文件是否存在, 异常:", e);
- exist = false;
- }
- return exist;
- }
-
- /**
- * 判断文件夹是否存在
- *
- * @param bucketName 存储桶
- * @param objectName 文件夹名称
- * @return
- */
- public boolean isFolderExist(String bucketName, String objectName) {
- boolean exist = false;
- try {
- Iterable<Result<Item>> results = minioClient.listObjects(
- ListObjectsArgs.builder().bucket(bucketName).prefix(objectName).recursive(false).build());
- for (Result<Item> result : results) {
- Item item = result.get();
- if (item.isDir() && objectName.equals(item.objectName())) {
- exist = true;
- }
- }
- } catch (Exception e) {
- log.error("[Minio工具类]>>>> 判断文件夹是否存在,异常:", e);
- exist = false;
- }
- return exist;
- }
-
- /**
- * 根据文件前置查询文件
- *
- * @param bucketName 存储桶
- * @param prefix 前缀
- * @param recursive 是否使用递归查询
- * @return MinioItem 列表
- * @throws Exception
- */
- public List<Item> getAllObjectsByPrefix(String bucketName,
- String prefix,
- boolean recursive) throws Exception {
- List<Item> list = new ArrayList<>();
- Iterable<Result<Item>> objectsIterator = minioClient.listObjects(
- ListObjectsArgs.builder().bucket(bucketName).prefix(prefix).recursive(recursive).build());
- if (objectsIterator != null) {
- for (Result<Item> o : objectsIterator) {
- Item item = o.get();
- list.add(item);
- }
- }
- return list;
- }
-
- /**
- * 获取文件流
- *
- * @param bucketName 存储桶
- * @param objectName 文件名
- * @return 二进制流
- */
- public InputStream getObject(String bucketName, String objectName) throws Exception {
- return minioClient.getObject(GetObjectArgs.builder().bucket(bucketName).object(objectName).build());
- }
-
- /**
- * 断点下载
- *
- * @param bucketName 存储桶
- * @param objectName 文件名称
- * @param offset 起始字节的位置
- * @param length 要读取的长度
- * @return 二进制流
- */
- public InputStream getObject(String bucketName, String objectName, long offset, long length) throws Exception {
- return minioClient.getObject(
- GetObjectArgs.builder()
- .bucket(bucketName)
- .object(objectName)
- .offset(offset)
- .length(length)
- .build());
- }
-
- /**
- * 获取路径下文件列表
- *
- * @param bucketName 存储桶
- * @param prefix 文件名称
- * @param recursive 是否递归查找,false:模拟文件夹结构查找
- * @return 二进制流
- */
- public Iterable<Result<Item>> listObjects(String bucketName, String prefix,
- boolean recursive) {
- return minioClient.listObjects(
- ListObjectsArgs.builder()
- .bucket(bucketName)
- .prefix(prefix)
- .recursive(recursive)
- .build());
- }
-
- /**
- * 使用MultipartFile进行文件上传
- *
- * @param bucketName 存储桶
- * @param file 文件名
- * @param objectName 对象名
- * @param contentType 类型
- * @return
- * @throws Exception
- */
- public ObjectWriteResponse uploadFile(String bucketName, MultipartFile file,
- String objectName, String contentType) throws Exception {
- InputStream inputStream = file.getInputStream();
- return minioClient.putObject(
- PutObjectArgs.builder()
- .bucket(bucketName)
- .object(objectName)
- .contentType(contentType)
- .stream(inputStream, inputStream.available(), -1)
- .build());
- }
-
- /**
- * 上传本地文件
- *
- * @param bucketName 存储桶
- * @param objectName 对象名称
- * @param fileName 本地文件路径
- */
- public ObjectWriteResponse uploadFile(String bucketName, String objectName,
- String fileName) throws Exception {
- return minioClient.uploadObject(
- UploadObjectArgs.builder()
- .bucket(bucketName)
- .object(objectName)
- .filename(fileName)
- .build());
- }
-
- /**
- * 通过流上传文件
- *
- * @param bucketName 存储桶
- * @param objectName 文件对象
- * @param inputStream 文件流
- */
- public ObjectWriteResponse uploadFile(String bucketName, String objectName, InputStream inputStream) throws Exception {
- return minioClient.putObject(
- PutObjectArgs.builder()
- .bucket(bucketName)
- .object(objectName)
- .stream(inputStream, inputStream.available(), -1)
- .build());
- }
-
- /**
- * 创建文件夹或目录
- *
- * @param bucketName 存储桶
- * @param objectName 目录路径
- */
- public ObjectWriteResponse createDir(String bucketName, String objectName) throws Exception {
- return minioClient.putObject(
- PutObjectArgs.builder()
- .bucket(bucketName)
- .object(objectName)
- .stream(new ByteArrayInputStream(new byte[]{}), 0, -1)
- .build());
- }
-
- /**
- * 获取文件信息, 如果抛出异常则说明文件不存在
- *
- * @param bucketName 存储桶
- * @param objectName 文件名称
- */
- public String getFileStatusInfo(String bucketName, String objectName) throws Exception {
- return minioClient.statObject(
- StatObjectArgs.builder()
- .bucket(bucketName)
- .object(objectName)
- .build()).toString();
- }
-
- /**
- * 拷贝文件
- *
- * @param bucketName 存储桶
- * @param objectName 文件名
- * @param srcBucketName 目标存储桶
- * @param srcObjectName 目标文件名
- */
- public ObjectWriteResponse copyFile(String bucketName, String objectName,
- String srcBucketName, String srcObjectName) throws Exception {
- return minioClient.copyObject(
- CopyObjectArgs.builder()
- .source(CopySource.builder().bucket(bucketName).object(objectName).build())
- .bucket(srcBucketName)
- .object(srcObjectName)
- .build());
- }
-
- /**
- * 删除文件
- *
- * @param bucketName 存储桶
- * @param objectName 文件名称
- */
- public void removeFile(String bucketName, String objectName) throws Exception {
- minioClient.removeObject(
- RemoveObjectArgs.builder()
- .bucket(bucketName)
- .object(objectName)
- .build());
- }
-
- /**
- * 批量删除文件
- *
- * @param bucketName 存储桶
- * @param keys 需要删除的文件列表
- * @return
- */
- public void removeFiles(String bucketName, List<String> keys) {
- List<DeleteObject> objects = new LinkedList<>();
- keys.forEach(s -> {
- objects.add(new DeleteObject(s));
- try {
- removeFile(bucketName, s);
- } catch (Exception e) {
- log.error("[Minio工具类]>>>> 批量删除文件,异常:", e);
- }
- });
- }
-
- /**
- * 获取文件外链
- *
- * @param bucketName 存储桶
- * @param objectName 文件名
- * @param expires 过期时间 <=7 秒 (外链有效时间(单位:秒))
- * @return url
- * @throws Exception
- */
- public String getPresignedObjectUrl(String bucketName, String objectName, Integer expires) throws Exception {
- GetPresignedObjectUrlArgs args = GetPresignedObjectUrlArgs.builder().expiry(expires).bucket(bucketName).object(objectName).build();
- return minioClient.getPresignedObjectUrl(args);
- }
-
- /**
- * 获得文件外链,失效时间默认是7天
- *
- * @param bucketName
- * @param objectName
- * @return url
- * @throws Exception
- */
- public String getPresignedObjectUrl(String bucketName, String objectName) throws Exception {
- GetPresignedObjectUrlArgs args = GetPresignedObjectUrlArgs.builder()
- .bucket(bucketName)
- .object(objectName)
- .method(Method.GET).build();
- return minioClient.getPresignedObjectUrl(args);
- }
-
- /**
- * 将URLDecoder编码转成UTF8
- *
- * @param str
- * @return
- * @throws UnsupportedEncodingException
- */
- public String getUtf8ByURLDecoder(String str) throws UnsupportedEncodingException {
- String url = str.replaceAll("%(?![0-9a-fA-F]{2})", "%25");
- return URLDecoder.decode(url, "UTF-8");
- }
-
-
- /****************************** Operate Files End ******************************/
-
- }
控制器
-
- import com.sifan.erp.config.MinioConfig;
- import com.sifan.erp.domain.MinioObject;
- import com.sifan.erp.dto.Result;
- import com.sifan.erp.service.MinioObjectService;
- import com.sifan.erp.utils.MinIOUtils;
- import io.minio.MinioClient;
- import io.minio.ObjectWriteResponse;
- import io.minio.StatObjectArgs;
- import io.minio.StatObjectResponse;
- import lombok.extern.slf4j.Slf4j;
- import org.springframework.web.bind.annotation.PostMapping;
- 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 javax.annotation.Resource;
- import javax.servlet.http.HttpServletResponse;
- import java.text.SimpleDateFormat;
- import java.util.Date;
- import java.util.UUID;
-
- @Slf4j
- @RestController
- @RequestMapping("/minio")
- public class MinioController {
- @Resource
- private MinIOUtils minIOUtils;
-
- @Resource
- private MinioConfig minioConfig;
- @Resource
- private MinioClient minioClient;
-
- @Resource
- private MinioObjectService minioObjectService;
-
- /**
- * @param file
- * @return
- */
- @PostMapping("/uploadCreative")
- public Result uploadCreativeScript(@RequestParam("file") MultipartFile file) {
- Result result = new Result();
- if (file == null) {
- result.setMessage("文件为空");
- return result;
- }
- final MinioObject minioObject = new MinioObject();
- // 1. 文件名处理
- String fileName = file.getOriginalFilename();
- String objectName = new SimpleDateFormat("yyyy/MM/dd/").format(new Date())
- + fileName.substring(0, fileName.indexOf('.') - 1)
- + "-" + UUID.randomUUID().toString().replaceAll("-", "")
- + fileName.substring(fileName.lastIndexOf("."));
- String contentType = file.getContentType();
- // 桶名称长度为3-63个字符,不能有大写字母
- String bucketName = "productcreative";
- try {
- //如果桶不存在,则创建桶
- minIOUtils.createBucket(bucketName);
- ObjectWriteResponse owr = minIOUtils.uploadFile(bucketName, file, objectName, contentType);
- result.setMessage("文件上传成功");
- minioObject.setBucketName(bucketName);
- minioObject.setContentType(contentType);
- minioObject.setCreatedTime(new Date());
- minioObject.setEtag(owr.etag());
- StatObjectResponse statObjectResponse = minioClient.statObject(StatObjectArgs.builder().bucket(bucketName).object(objectName).build());
- minioObject.setLength(statObjectResponse.size());
- minioObject.setName(objectName);
-
- //插入MinioObject数据,查询Id
- Integer minioObjectId = minioObjectService.insertSelectId(minioObject);
- result.setData(minioObjectId);
-
- } catch (Exception e) {
- result.setMessage("文件上传失败:" + e.getMessage());
- e.printStackTrace();
- }
- return result;
- }
-
- //https://blog.csdn.net/aaa58962458/article/details/120764754
- @PostMapping("downloadCreative")
- public Result downloadCreative(@RequestParam("minioObjectId") Integer minioObjectId, HttpServletResponse response) throws Exception {
- Result result = new Result();
- if (minioObjectId == null) {
- result.setMessage("文件id为空");
- return result;
- }
- MinioObject minioObjectById = minioObjectService.getMinioObjectById(minioObjectId);
- String bucketName = minioObjectById.getBucketName();
- String name = minioObjectById.getName();
- boolean exists = minIOUtils.bucketExists(bucketName);
- //桶不存在
- if (!exists) {
- result.setMessage("桶不存在");
- return result;
- }
- boolean objectExist = minIOUtils.isObjectExist(bucketName, name);
- if (!objectExist) {
- result.setMessage("文件不存在");
- return result;
- }
- // 获取外链,链接失效时间7天
- String url = minIOUtils.getPresignedObjectUrl(bucketName, name);
- result.setData(url);
- return result;
- }
-
- }
Vue前端上传
- <el-upload
- class="upload-demo"
- :action="url+uploadUrl"
- :on-change="handleChange"
- :file-list="fileList"
- name="file"
- >
- <el-button size="small" type="primary">点击上传</el-button>
- </el-upload>
-
-
-
-
-
- data() {
- return {
- url: request.defaults.baseURL,
- uploadUrl: '/minio/uploadCreative',
- }
- }
-
-
Vue下载,后端生成外链实现下载
- <el-button
- size="small"
- type="primary"
- style="margin-left: 15px"
- @click="creativeScriptDownload(props.row.creativeScript)"
- >点击下载
- </el-button>
-
-
-
-
- creativeScriptDownload: function(creativeScript) {
- request.post('/minio/downloadCreative?minioObjectId=' + creativeScript).then(res => {
- window.open(res.data)
- }).catch(err => {
- this.$message({
- type: 'info',
- message: '创意脚本下载失败' + err.message
- })
- })
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。