windows环境下搭建minio步骤
1.从minio官网进行查看详细信息
地址:https://min.io/里面有详细的配置信息搭建成功之后如下如所示:用户名密码默认情况下为 username:minioadmin password:minioadmin
2.搭建成功之后的访问
地址:服务ip 端口9000http//127.0.0.1:9000 用户名密码为默认:minioadmin 创建桶时候要注意桶的名称
springboot整合和minio的步骤如下
1.pom坐标的指定
<dependency><groupId>io.minio</groupId><artifactId>minio</artifactId><version>8.2.2</version></dependency><!-- Hutool --><dependency><groupId>cn.hutool</groupId><artifactId>hutool-all</artifactId><version>5.8.18</version></dependency>
2.配置文件的设置如下
package com.java.javamethod.conf;import io.minio.MinioClient;
import lombok.SneakyThrows;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;import javax.annotation.Resource;@Configuration
@EnableConfigurationProperties(MinioProperties.class)
@ConditionalOnProperty(value = "oss.name", havingValue = "minio")
public class MinioConfiguration {@Resourceprivate MinioProperties ossProperties;@Bean@SneakyThrowspublic MinioClient minioClient() {return MinioClient.builder().endpoint(ossProperties.getEndpoint()).credentials(ossProperties.getAccessKey(), ossProperties.getSecretKey()).build();}}
package com.java.javamethod.conf;import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import java.util.List;
@Data
@ConfigurationProperties(prefix = MinioProperties.PREFIX)
public class MinioProperties {public static final String PREFIX = "oss";private String name;private String endpoint;private String accessKey;private String secretKey;private String bucketName = "qditwei";private List<String> fileExt;}
3.minio工具类的封装
package com.java.javamethod.service;import com.java.javamethod.domain.OssFile;
import org.springframework.web.multipart.MultipartFile;import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.List;
public interface OssTemplate {boolean bucketExists(String bucketName);OssFile getOssInfo(String fileName);OssFile upLoadFile(String folderName, String fileName, MultipartFile file);OssFile upLoadFile(String folderName, String fileName, String suffix, InputStream stream);boolean removeFile(String fileName);boolean removeFiles(List<String> fileNames);void downloadFile(HttpServletResponse response, String fileName, String filePath);
}package com.java.javamethod.util;import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.text.StrPool;
import cn.hutool.core.util.ObjectUtil;
import com.java.javamethod.conf.MinioProperties;
import com.java.javamethod.domain.OssFile;
import com.java.javamethod.service.OssTemplate;
import io.minio.*;
import io.minio.http.Method;
import io.minio.messages.DeleteObject;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.web.multipart.MultipartFile;import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;
import java.util.stream.Stream;@Slf4j
@Service
public class MinioTemplate implements OssTemplate {@Resourceprivate MinioClient client;@Resourceprivate MinioProperties ossProperties;private static final String DATE_FORMAT = "yyyyMMdd";private static final String ENCODING = "UTF-8";@Overridepublic boolean bucketExists(String bucketName) {try {return client.bucketExists(BucketExistsArgs.builder().bucket(getBucketName(bucketName)).build());} catch (Exception e) {log.error("minio bucketExists Exception:{}", e);}return false;}public void makeBucket(String bucketName) {try {if (!client.bucketExists(BucketExistsArgs.builder().bucket(getBucketName(bucketName)).build())) {client.makeBucket(MakeBucketArgs.builder().bucket(getBucketName(bucketName)).build());log.info("minio makeBucket success bucketName:{}", bucketName);}} catch (Exception e) {log.error("minio makeBucket Exception:{}", e);}}@Overridepublic OssFile getOssInfo(String fileName) {try {StatObjectResponse stat = client.statObject(StatObjectArgs.builder().bucket(getBucketName(ossProperties.getBucketName())).object(fileName).build());OssFile ossFile = new OssFile();ossFile.setName(ObjectUtil.isEmpty(stat.object()) ? fileName : stat.object());ossFile.setFilePath(ossFile.getName());ossFile.setDomain(getOssHost(ossProperties.getBucketName()));ossFile.setHash(String.valueOf(stat.hashCode()));ossFile.setSize(stat.size());ossFile.setPutTime(DateUtil.date(stat.lastModified().toLocalDateTime()));ossFile.setContentType(stat.contentType());return ossFile;} catch (Exception e) {log.error("minio getOssInfo Exception:{}", e);}return null;}@Override@SneakyThrowspublic OssFile upLoadFile(String folderName, String fileName, MultipartFile file) throws RuntimeException {if (file == null || file.isEmpty()) {throw new RuntimeException("文件不能为空");}if (file.getSize() > 5 * 1024 * 1024) {throw new RuntimeException("文件大小不能超过5M");}String suffix = getFileExtension(file.getOriginalFilename());try {return upLoadFile(folderName, fileName, suffix, file.getInputStream());} catch (Exception e) {log.error("minio upLoadFile Exception:{}", e);throw new RuntimeException("文件上传失败,请重新上传或联系管理员");}}public static String getFileExtension(String fullName) {Assert.notNull(fullName, "minio file fullName is null.");String fileName = new File(fullName).getName();int dotIndex = fileName.lastIndexOf('.');return (dotIndex == -1) ? "" : fileName.substring(dotIndex + 1);}@Overridepublic OssFile upLoadFile(String folderName, String fileName, String suffix, InputStream stream) {try {return upLoadFile(ossProperties.getBucketName(), folderName, fileName, suffix, stream,"application/octet" + "-stream");} catch (Exception e) {log.error("minio upLoadFile Exception:{}", e);}return null;}@SneakyThrowspublic OssFile upLoadFile(String bucketName, String folderName, String fileName, String suffix, InputStream stream,String contentType) {if (!bucketExists(bucketName)) {log.info("minio bucketName is not creat");makeBucket(bucketName);}OssFile file = new OssFile();String originalName = fileName;String filePath = getFilePath(folderName, fileName, suffix);client.putObject(PutObjectArgs.builder().bucket(getBucketName(bucketName)).object(filePath).stream(stream, stream.available(), -1).contentType(contentType).build());file.setOriginalName(originalName);file.setName(filePath);file.setDomain(getOssHost(bucketName));file.setFilePath(filePath);stream.close();log.info("minio upLoadFile success, filePath:{}", filePath);return file;}@Overridepublic boolean removeFile(String fileName) {try {client.removeObject(RemoveObjectArgs.builder().bucket(getBucketName(ossProperties.getBucketName())).object(fileName).build());log.info("minio removeFile success, fileName:{}", fileName);return true;} catch (Exception e) {log.error("minio removeFile fail, fileName:{}, Exception:{}", fileName, e);}return false;}@Overridepublic boolean removeFiles(List<String> fileNames) {try {Stream<DeleteObject> stream = fileNames.stream().map(DeleteObject::new);client.removeObjects(RemoveObjectsArgs.builder().bucket(getBucketName(ossProperties.getBucketName())).objects(stream::iterator).build());log.info("minio removeFiles success, fileNames:{}", fileNames);return true;} catch (Exception e) {log.error("minio removeFiles fail, fileNames:{}, Exception:{}", fileNames, e);}return false;}@Overridepublic void downloadFile(HttpServletResponse response, String fileName, String filePath) {GetObjectResponse is = null;try {GetObjectArgs getObjectArgs =GetObjectArgs.builder().bucket(ossProperties.getBucketName()).object(filePath).build();is = client.getObject(getObjectArgs);response.setContentType("application/x-msdownload");response.setCharacterEncoding(ENCODING);response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(fileName, ENCODING));IoUtil.copy(is, response.getOutputStream());log.info("minio downloadFile success, filePath:{}", filePath);} catch (Exception e) {log.error("minio downloadFile Exception:{}", e);} finally {IoUtil.close(is);}}public String getPresignedObjectUrl(String bucketName, String fileName, Integer expires) {String link = "";try {link = client.getPresignedObjectUrl(GetPresignedObjectUrlArgs.builder().method(Method.GET).bucket(getBucketName(bucketName)).object(fileName).expiry(expires).build());} catch (Exception e) {log.error("minio getPresignedObjectUrl is fail, fileName:{}", fileName);}return link;}private String getBucketName(String bucketName) {return bucketName;}private String getFilePath(String folderName, String originalFilename, String suffix) {return StrPool.SLASH + String.join(StrPool.SLASH, folderName, DateUtil.date().toString(DATE_FORMAT),originalFilename) + StrPool.C_UNDERLINE + DateUtil.current() + StrPool.DOT + suffix;}public String getOssHost(String bucketName) {return ossProperties.getEndpoint() + StrPool.SLASH + getBucketName(bucketName);}}
4.swagger功能的验证
package com.java.javamethod.controller;import com.java.javamethod.domain.OssFile;
import com.java.javamethod.util.MinioTemplate;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;import javax.annotation.Resource;
@RestController
@Api(tags = "文件控制器", description = "文件管理控制器")
public class FileController {@ResourceMinioTemplate minioTemplate;@PostMapping("/upload")@ApiImplicitParams(value = {@ApiImplicitParam(name = "folderName", value = "文件路径", required = true, dataType = "String"),@ApiImplicitParam(name = "fileName", value = "文件名", required = true, dataType = "String")}) public OssFile upload(String folderName, String fileName,@RequestPart MultipartFile file) {return minioTemplate.upLoadFile( folderName, fileName, file);}}