前言:
确保已经安装了minio的服务端
代码:
pom.xml

1
2
3
4
5

io.minio
minio
7.0.2

1 配置类

创建项目 操作 MinIOpom.xml 相关依赖


com.alibaba
fastjson
LATEST


org.springframework.boot
spring-boot-starter-thymeleaf


org.springframework.boot
spring-boot-starter-web


org.projectlombok
lombok
true


io.minio
minio
7.0.1


commons-io
commons-io
2.6

编辑配置文件application.properties修改MinIO相关配置

server.port=80
spring.application.name=book-minio

spring.thymeleaf.cache=false

spring.servlet.multipart.max-file-size = 10MB
spring.servlet.multipart.max-request-size=100MB

minio.endpoint=http://192.168.1.6:9000
minio.accesskey=minio
minio.secretKey=Aa123456
连接 MinIO 配置

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Data
@ConfigurationProperties(prefix = “minio”)
@Component
public class MinioProp {
private String endpoint;
private String accesskey;
private String secretKey;
}
创建 MinioClient

import io.minio.MinioClient;
import io.minio.errors.InvalidEndpointException;
import io.minio.errors.InvalidPortException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MinioConfiguration {
@Autowired
private MinioProp minioProp;

@Bean
public MinioClient minioClient() throws InvalidPortException, InvalidEndpointException {
MinioClient client = new MinioClient(minioProp.getEndpoint(), minioProp.getAccesskey(), minioProp.getSecretKey());
return client;
}
}
MinIO 查看桶列表,存入,删除 操作 MinioController

import com.alibaba.fastjson.JSON;
import com.lab.book.minio.common.Res;
import io.minio.MinioClient;
import io.minio.ObjectStat;
import io.minio.PutObjectOptions;
import io.minio.Result;
import io.minio.messages.Item;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.util.
;

@Slf4j
@RestController
public class MinioController {
@Autowired
private MinioClient minioClient;

private static final String MINIO_BUCKET = “mybucket”;

@GetMapping(“/list”)
public List list(ModelMap map) throws Exception {
Iterable> myObjects = minioClient.listObjects(MINIO_BUCKET);
Iterator> iterator = myObjects.iterator();
List items = new ArrayList<>();
String format = “{‘fileName’:’%s’,’fileSize’:’%s’}”;
while (iterator.hasNext()) {
Item item = iterator.next().get();
items.add(JSON.parse(String.format(format, item.objectName(), formatFileSize(item.size()))));
}
return items;
}

@PostMapping(“/upload”)
public Res upload(@RequestParam(name = “file”, required = false) MultipartFile[] file) {
Res res = new Res();
res.setCode(500);

if (file == null || file.length == 0) {
res.setMessage(“上传文件不能为空”);
return res;
}

List orgfileNameList = new ArrayList<>(file.length);

for (MultipartFile multipartFile : file) {
String orgfileName = multipartFile.getOriginalFilename();
orgfileNameList.add(orgfileName);

try {
InputStream in = multipartFile.getInputStream();
minioClient.putObject(MINIO_BUCKET, orgfileName, in, new PutObjectOptions(in.available(), -1));
in.close();
} catch (Exception e) {
log.error(e.getMessage());
res.setMessage(“上传失败”);
return res;
}
}

Map data = new HashMap();
data.put(“bucketName”, MINIO_BUCKET);
data.put(“fileName”, orgfileNameList);
res.setCode(200);
res.setMessage(“上传成功”);
res.setData(data);
return res;
}

@RequestMapping(“/download/{fileName}”)
public void download(HttpServletResponse response, @PathVariable(“fileName”) String fileName) {
InputStream in = null;
try {
ObjectStat stat = minioClient.statObject(MINIO_BUCKET, fileName);
response.setContentType(stat.contentType());
response.setHeader(“Content-Disposition”, “attachment;filename=” + URLEncoder.encode(fileName, “UTF-8”));

in = minioClient.getObject(MINIO_BUCKET, fileName);
IOUtils.copy(in, response.getOutputStream());
} catch (Exception e) {
log.error(e.getMessage());
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
log.error(e.getMessage());
}
}
}
}

@DeleteMapping(“/delete/{fileName}”)
public Res delete(@PathVariable(“fileName”) String fileName) {
Res res = new Res();
res.setCode(200);
try {
minioClient.removeObject(MINIO_BUCKET, fileName);
} catch (Exception e) {
res.setCode(500);
log.error(e.getMessage());
}
return res;
}

private static String formatFileSize(long fileS) {
DecimalFormat df = new DecimalFormat(“#.00”);
String fileSizeString = “”;
String wrongSize = “0B”;
if (fileS == 0) {
return wrongSize;
}
if (fileS < 1024) {
fileSizeString = df.format((double) fileS) + “ B”;
} else if (fileS < 1048576) {
fileSizeString = df.format((double) fileS / 1024) + “ KB”;
} else if (fileS < 1073741824) {
fileSizeString = df.format((double) fileS / 1048576) + “ MB”;
} else {
fileSizeString = df.format((double) fileS / 1073741824) + “ GB”;
}
return fileSizeString;
}
}
Res 文件

import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;

import java.io.Serializable;

@lombok.Data
@AllArgsConstructor
@NoArgsConstructor
public class Res implements Serializable {
private static final long serialVersionUID = 1L;
private Integer code;
private Object data = “”;
private String message = “”;
}
路由文件 RouterController

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class RouterController {
@GetMapping({“/“, “/index.html”})
public String index() {
return “index”;
}

@GetMapping({“/upload.html”})
public String upload() {
return “upload”;
}
}


2MinioUtil

public class MinioUtil {
private static String minio_url;
private static String minio_name;
private static String minio_pass;
private static String minio_bucketName;

/

@Title: uploadImage
@Description:上传图片
@param inputStream
@param suffix
@return
@throws Exception
/
public static JSONObject uploadImage(InputStream inputStream, String suffix) throws Exception {
return upload(inputStream, suffix, “image/jpeg”);
}

/

@Title: uploadVideo
@Description:上传视频
@param inputStream
@param suffix
@return
@throws Exception
/
public static JSONObject uploadVideo(InputStream inputStream, String suffix) throws Exception {
return upload(inputStream, suffix, “video/mp4”);
}

/**
@Title: uploadVideo
@Description:上传文件
@param inputStream
@param suffix
@return
@throws Exception
/
public static JSONObject uploadFile(InputStream inputStream, String suffix) throws Exception {
return upload(inputStream, suffix, “application/octet-stream”);
}

/
上传字符串大文本内容

@Title: uploadString
@Description:描述方法
@param str
@return
@throws Exception
/
public static JSONObject uploadString(String str) throws Exception {
if (!StringUtils.notNullAndEmpty(str)) {
return new JSONObject();
}
InputStream inputStream = new ByteArrayInputStream(str.getBytes());
return upload(inputStream, null, “text/html”);
}

/

@Title: upload
@Description:上传主功能
@return
@throws Exception
*/
private static JSONObject upload(InputStream inputStream, String suffix, String contentType) throws Exception {
JSONObject map = new JSONObject();
PropertiesLoader p = new PropertiesLoader(“system.properties”);
minio_url = p.getProperty(“minio_url”);
minio_name = p.getProperty(“minio_name”);
minio_pass = p.getProperty(“minio_pass”);
minio_bucketName = p.getProperty(“minio_bucketName”);
MinioClient minioClient = new MinioClient(minio_url, minio_name, minio_pass);
SimpleDateFormat sdf = new SimpleDateFormat(“yyyyMM”);
String ymd = sdf.format(new Date());
String objectName = ymd + “/“ + UUID.randomUUID().toString() + (suffix != null ? suffix : “”);
minioClient.putObject(minio_bucketName, objectName, inputStream, contentType);
String url = minioClient.getObjectUrl(minio_bucketName, objectName);
map.put(“flag”, “0”);
map.put(“mess”, “上传成功”);
map.put(“url”, url);
map.put(“urlval”, url);
map.put(“path”, minio_bucketName + “/“ + objectName);
return map;
}
}
[

](https://blog.csdn.net/shenjianzhuang/article/details/79868213)