minio下载
提取链接:
https://pan.baidu.com/s/10DIqrOvAWk8TlX0pPJdi5Q
提取码:isak
以下是代码是实现
package com.jspxcms.ext.web.back;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.google.common.io.ByteStreams;
import com.jspxcms.ext.web.utils.PageUtil;
import com.jspxcms.ext.web.vo.FileVo;
import io.minio.MinioClient;
import io.minio.ObjectStat;
import io.minio.PutObjectOptions;
import io.minio.Result;
import io.minio.errors.*;
import io.minio.messages.Bucket;
import io.minio.messages.Item;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.DecimalFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.*;
/**
* @author linyh
* @version 1.0
* @email [email protected]
* @date 2021/2/4 15:00
*/
@Controller
@RequestMapping("/file")
public class FileUploadController {
private static MinioClient minioClient;
// minio服务器地址
private static final String endpoint = "http://127.0.0.1:9001";
static {
try {
// minioClient初始化,设置endpoint和连接minio服务所需的密码
minioClient = new MinioClient(endpoint, "xxx", "xxx");
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 文件上传
*
* @param file 文件
* @param bucketName 文件夹名称(minio上对应的bucket相当于文件夹)
* @return
* @throws Exception
*/
@ResponseBody
@RequestMapping(value = "/upload", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
public String uploadFile(MultipartFile file, String bucketName) throws Exception {
JSONObject res = new JSONObject();
// 判断上传文件是否为空
if (null == file || 0 == file.getSize()) {
return "文件不能为空";
}
// 判断文件夹是否存在
boolean bucketExists = minioClient.bucketExists(bucketName);
// 如果文件夹不存在则创建
if (!bucketExists) {
// 创建
minioClient.makeBucket(bucketName);
}
// 文件名
String originalFilename = file.getOriginalFilename();
// 上传操作
minioClient.putObject(bucketName, originalFilename, file.getInputStream(), new PutObjectOptions(file.getSize(), 0L));
return "文件上传成功";
}
/**
* 获取文件列表
*
* @param pageNum 页码
* @param pageSize 一页的数量
* @return
* @throws Exception
*/
@ResponseBody
@RequestMapping(value = "/fileList", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
public String getFileList(Integer pageNum, Integer pageSize) throws Exception {
DecimalFormat df = new DecimalFormat("0.00");
List buckets = minioClient.listBuckets();
List list = new ArrayList<>(32);
if (!buckets.isEmpty()) {
buckets.forEach(s -> {
try {
// 得到bucket下的文件
Iterable> results = minioClient.listObjects(s.name());
// 循环遍历获取每一个文件对象
results.forEach(g -> {
try {
FileVo fileVo = new FileVo();
fileVo.setBucketName(s.name()); // 文件夹名称
fileVo.setFileName(g.get().objectName()); // 文件名称
fileVo.setUpdateTime(localDateTime2Date(g.get().lastModified().toLocalDateTime())); // 文件上传时间
Long size = g.get().size();
if (size > (1024 * 1024)) {
fileVo.setFileSize(df.format(((double) size / 1024 / 1024)) + "MB"); // 文件大小,如果超过1M,则把单位换成MB
} else if (size > 1024) {
fileVo.setFileSize(df.format(((double) size / 1024)) + "KB"); // 文件大小,如果没超过1M但是超过1000字节,则把单位换成KB
} else {
fileVo.setFileSize( size + "bytes"); // // 文件大小,如果没超过1000字节,则把单位换成bytes
}
list.add(fileVo);
} catch (ErrorResponseException e) {
e.printStackTrace();
} catch (InsufficientDataException e) {
e.printStackTrace();
} catch (InternalException e) {
e.printStackTrace();
} catch (InvalidBucketNameException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (InvalidResponseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (XmlParserException e) {
e.printStackTrace();
}
});
} catch (XmlParserException e) {
e.printStackTrace();
}
});
}
JSONObject res = new JSONObject();
res.put("code", 200);
res.put("message", "获取文件列表成功");
// 按最后上传时间排序
list.sort(new Comparator() {
@Override
public int compare(FileVo o1, FileVo o2) {
return o2.getUpdateTime().compareTo(o1.getUpdateTime());
}
});
// 分页
List returnList = PageUtil.startPage(list, pageNum, pageSize);
res.put("list", returnList);
ObjectMapper mapper = new ObjectMapper();
String s = mapper.writeValueAsString(res);
return s;
}
/**
* 文件下载(浏览器端下载)
*
* @param bucketName 文件夹名称
* @param filetName 文件名称
* @param response
* @throws Exception
*/
@ResponseBody
@RequestMapping(value = "/download", method = RequestMethod.GET)
public void download(String bucketName, String filetName, HttpServletResponse response) throws Exception {
// 根据文件夹名称和文件名称找到对应文件对象
ObjectStat stat = minioClient.statObject(bucketName, filetName);
byte[] buffer = new byte[1024];
int length = (int) stat.length();
try (InputStream inputStream = minioClient.getObject(bucketName, filetName);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(length)) {
ByteStreams.copy(inputStream, outputStream);
buffer = outputStream.toByteArray();
} catch (Exception e) {
e.printStackTrace();
}
response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
response.setHeader("Content-disposition", "attachment; filename=" + new String(filetName.getBytes("utf-8"), "ISO8859-1"));
response.getOutputStream().write(buffer);
response.flushBuffer();
response.getOutputStream().close();
}
/**
* 删除文件
*
* @param bucketName 文件夹名称
* @param filetName 文件名称
* @return
* @throws Exception
*/
@ResponseBody
@RequestMapping(value = "/remove", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
public JSONObject removeFile(String bucketName, String filetName) throws Exception {
// 删除文件夹下的对应文件
minioClient.removeObject(bucketName, filetName);
JSONObject res = new JSONObject();
res.put("code", 200);
res.put("message", "删除文件成功");
return res;
}
/**
* 删除文件夹
*
* @param bucketName 文件夹名称
* @return
* @throws Exception
*/
@ResponseBody
@RequestMapping(value = "/delete.do", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
public JSONObject removeBucket(String bucketName) throws Exception {
// 删除文件夹
minioClient.removeBucket(bucketName);
JSONObject res = new JSONObject();
res.put("code", 200);
res.put("message", "删除文件夹成功");
return res;
}
/**
* LocalDateTime转换为Date
* @param localDateTime
*/
public Date localDateTime2Date( LocalDateTime localDateTime){
ZoneId zoneId = ZoneId.systemDefault();
ZonedDateTime zdt = localDateTime.atZone(zoneId);
Date date = Date.from(zdt.toInstant());
Calendar cal=Calendar.getInstance();
cal.setTime(date);
// 由于获取的时间存在时间差,我这里手动加上16小时
cal.add(Calendar.HOUR_OF_DAY, 16);
date = cal.getTime();
return date;
}
}
FileVo
package com.jspxcms.ext.web.vo;
import com.fasterxml.jackson.annotation.JsonFormat;
import java.util.Date;
public class FileVo {
private String bucketName; // 文件夹
private String fileName; // 文件名
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date updateTime; // 最后修改时间
private String fileSize; // 文件大小
public String getBucketName() {
return bucketName;
}
public void setBucketName(String bucketName) {
this.bucketName = bucketName;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
public String getFileSize() {
return fileSize;
}
public void setFileSize(String fileSize) {
this.fileSize = fileSize;
}
}
附上分页工具类
package com.jspxcms.ext.web.utils;
import java.util.List;
/**
* 自定义分页工具
*/
public class PageUtil {
/**
* 开始分页
* @param list 需要进行分页的集合列表
* @param pageNum 页码
* @param pageSize 每页多少条数据
* @return
*/
public static List startPage(List list, Integer pageNum,
Integer pageSize) {
if (list == null) {
return null;
}
if (list.size() == 0) {
return null;
}
if(null == pageNum || "".equals(pageNum.toString())){
pageNum = 1;
}
if(null == pageSize || "".equals(pageSize.toString())){
pageSize = 10;
}
Integer count = list.size(); // 记录总数
Integer pageCount = 0; // 页数
if (count % pageSize == 0) {
pageCount = count / pageSize;
} else {
pageCount = count / pageSize + 1;
}
int fromIndex = 0; // 开始索引
int toIndex = 0; // 结束索引
if (pageNum != pageCount) {
fromIndex = (pageNum - 1) * pageSize;
toIndex = fromIndex + pageSize;
} else {
fromIndex = (pageNum - 1) * pageSize;
toIndex = count;
}
List pageList = list.subList(fromIndex, toIndex);
return pageList;
}
}