pom.xml
<!-- minio依赖 -->
<dependency>
<groupId>io.minio</groupId>
<artifactId>minio</artifactId>
<version>8.2.1</version>
</dependency>
application.yml
minio: # minio
endpoint: http://xxx.xxx.xxx.xxx:9000
accessKey: admin
secretKey: admin123
secure: false
bucketName: test
secure(表示的是是否使用https)
MinioConfig
import io.minio.MinioClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MinIoConfig {
@Autowired
private MinioProperties minioProperties;
@Bean
public MinioClient uploadFile() {
MinioClient minioClient = MinioClient.builder()
.endpoint(minioProperties.getEndpoint())
.credentials(minioProperties.getAccessKey(), minioProperties.getSecretKey()).build();
return minioClient;
}
}
MinioProperties
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Data
@Component
@ConfigurationProperties(prefix = "minio")
public class MinioProperties {
private String endpoint;
private String accessKey;
private String secretKey;
}
MinIoUtils
import com.nineclock.system.config.MinioProperties;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.multipart.MultipartFile;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
@Slf4j
@Configuration
public class MinIoUtils {
@Value("${minio.bucketName}")
private String bucketName;
@Autowired
private MinioProperties minioProperties;
@Autowired
private MinioClient minioClient;
public String uploadFile(String fileName, MultipartFile file) {
fileName = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS")) + "-" + fileName;
try {
InputStream in = file.getInputStream();
List<String> fileNameList = new ArrayList<>();
fileNameList.add(fileName);
minioClient.putObject(
PutObjectArgs.builder().bucket(bucketName) // 桶名
.object(fileName) // 文件
.stream(in,file.getSize(),-1) // 文件输出流
.contentType(file.getContentType()) // 文件格式
.build());
String url = minioProperties.getEndpoint() + "/" + bucketName + "/" + fileName;
log.info("url:" + url); // 前端直传需要的url地址
return url;
} catch (Exception e) {
System.out.println("Error occurred: " + e);
}
return null;
}
}