- 编写minio的pom.xml 依赖
<dependency>
<groupId>io.miniogroupId>
<artifactId>minioartifactId>
<version>8.0.3version>
dependency>
- 编写minio配置文件application.yml
minio:
endpoint: http://x.xxx.xxx.18:9000
bucket: mall4cloud
accessKey: admin
secretKey: admin123456
- 编写minio服务接口
package cn.sh.ideal.service;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import cn.sh.ideal.result.ServerResponseEntity;
import io.minio.errors.*;
import org.springframework.web.multipart.MultipartFile;
public interface MinIoService {
ServerResponseEntity<String> upload(MultipartFile multipart) throws IOException, ServerException, InsufficientDataException, InternalException, InvalidResponseException, InvalidKeyException, NoSuchAlgorithmException, XmlParserException, ErrorResponseException;
ServerResponseEntity<Boolean> delete(String path);
ServerResponseEntity<String> getPresignedObjectUrl(String path);
ServerResponseEntity<String> download(String path);
ServerResponseEntity download(String path, HttpServletRequest request , HttpServletResponse response);
}
- 编写minio实现类
package cn.sh.ideal.service.impl;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.concurrent.TimeUnit;
import cn.hutool.core.util.StrUtil;
import cn.sh.ideal.config.MinIOConfigProperties;
import cn.sh.ideal.result.ServerResponseEntity;
import cn.sh.ideal.service.MinIoService;
import io.minio.*;
import io.minio.errors.*;
import io.minio.http.Method;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
@Slf4j
@RequiredArgsConstructor
@Service
public class MinIOImpl implements MinIoService {
private final MinioClient minClient;
private final MinIOConfigProperties configProperties;
@Override
public ServerResponseEntity<String> upload(MultipartFile multipart) throws IOException, ServerException, InsufficientDataException, InternalException, InvalidResponseException, InvalidKeyException, NoSuchAlgorithmException, XmlParserException, ErrorResponseException {
String path= StrUtil.uuid();
boolean found = minClient.bucketExists(BucketExistsArgs.builder().bucket(configProperties.getBucket()).build());
if (!found) {
minClient.makeBucket(MakeBucketArgs.builder().bucket(configProperties.getBucket()).build());
} else {
System.out.println("桶名="+configProperties.getBucket()+" 已存在");
}
minClient.putObject(
PutObjectArgs.builder()
.bucket(configProperties.getBucket())
.object(path)
.contentType(multipart.getContentType())
.stream(multipart.getInputStream(),multipart.getSize(),-1)
.build()
);
String filePath = new StringBuffer(configProperties.getEndpoint())
.append("/")
.append(configProperties.getBucket())
.append("/")
.append(path)
.toString();
return ServerResponseEntity.success(filePath);
}
@SneakyThrows
@Override
public ServerResponseEntity<Boolean> delete(String path) {
minClient.removeObject(RemoveObjectArgs
.builder()
.bucket(configProperties.getBucket())
.object(path)
.build()
);
return null;
}
@SneakyThrows
@Override
public ServerResponseEntity<String> getPresignedObjectUrl(String path){
String objectUrl = minClient.getPresignedObjectUrl(GetPresignedObjectUrlArgs
.builder()
.bucket(configProperties.getBucket())
.object(path)
.expiry(10, TimeUnit.MINUTES)
.method(Method.GET).build());
return ServerResponseEntity.success(objectUrl);
}
@SneakyThrows
@Override
public ServerResponseEntity<String> download(String path){
minClient.downloadObject(DownloadObjectArgs
.builder()
.bucket(configProperties.getBucket())
.object(path)
.filename("C:/eladmin/avatar/a.jpg")
.build()
);
return ServerResponseEntity.success();
}
@SneakyThrows
@Override
public ServerResponseEntity download(String path, HttpServletRequest request, HttpServletResponse response){
try {
InputStream inputStream = minClient.getObject(GetObjectArgs
.builder()
.bucket(configProperties.getBucket())
.object(path)
.build());
response.setCharacterEncoding(request.getCharacterEncoding());
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment; filename=" + "a.jpg");
IOUtils.copy(inputStream, response.getOutputStream());
response.flushBuffer();
}finally {
}
return ServerResponseEntity.success();
}
}
- 编写minio控制类
package cn.sh.ideal.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import cn.sh.ideal.result.ServerResponseEntity;
import cn.sh.ideal.service.MinIoService;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
@Slf4j
@RequiredArgsConstructor
@RestController
@RequestMapping("/minIO")
public class MinIOController {
private final MinIoService minIoService;
@SneakyThrows
@PostMapping("/upload")
public ServerResponseEntity<String> uploadFile(MultipartFile multipart){
return minIoService.upload(multipart);
}
@GetMapping("/delete/{path}")
public ServerResponseEntity delete(@PathVariable("path") String path){
minIoService.delete(path);
return ServerResponseEntity.success();
}
@GetMapping("/getUrl/{path}")
public ServerResponseEntity getUrl(@PathVariable("path") String path){
return minIoService.getPresignedObjectUrl(path);
}
@GetMapping("/download/{path}")
public ServerResponseEntity download(@PathVariable("path") String path){
return minIoService.download(path);
}
@PostMapping("/downloadHttp/{path}")
public ServerResponseEntity download(@PathVariable("path") String path, HttpServletRequest request, HttpServletResponse response){
return minIoService.download(path,request,response);
}
}
- 编写结果集
package cn.sh.ideal.result;
public enum ResponseEnum {
OK("00000", "ok"),
SHOW_FAIL("A00001", ""),
METHOD_ARGUMENT_NOT_VALID("A00002", ""),
HTTP_MESSAGE_NOT_READABLE("A00003", "请求参数格式有误"),
UNAUTHORIZED("A00004", "Unauthorized"),
EXCEPTION("A00005", "服务器出了点小差"),
DATA_ERROR("A00007", "数据异常,请刷新后重新操作"),
CLEAN_TOKEN("A00008", "clean token"),
REFRESH_TOKEN_EXIST("A00009", "refresh token exist"),
DATA_INCOMPLETE("A00010", "数据不完整"),
SPU_NOT_EXIST("A01000", "spu not exist"),
SHOP_CART_NOT_EXIST("A02000", "shop cart not exist"),
ORDER_NOT_EXIST("A03000", "order not exist"),
REPEAT_ORDER("A03002", "please don't repeat order"),
ORDER_EXPIRED("A03003", "order expired"),
ORDER_PAYED("A03007", "order payed"),
ORDER_NO_DELIVERY("A03008", "order no delivery"),
NOT_STOCK("A03010", "not stock"),
ORDER_NOT_FINISH_OR_CLOSE("A03011", "order not finish or close"),
ORDER_NOT_PAYED("A03012", "order not payed"),
ORDER_HAS_FAILED("A03013", "order has failed"),
REFUND_NOT_PERMISSION("A03024", "refund not permission"),
REFUND_STATUS_CHECK("A03034", "refund status check"),
SOCIAL_ACCOUNT_NOT_BIND("A04001", "social account not bind"),
BIZ_TEMP_SESSION_KEY_EXPIRE("A04002", "biz temp session key expire"),
ACCOUNT_NOT_REGISTER("A04003", "account not register");
private final String code;
private final String msg;
public String value() {
return code;
}
public String getMsg() {
return msg;
}
ResponseEnum(String code, String msg) {
this.code = code;
this.msg = msg;
}
@Override
public String toString() {
return "ResponseEnum{" + "code='" + code + '\'' + ", msg='" + msg + '\'' + "} " + super.toString();
}
}
package cn.sh.ideal.result;
import java.io.Serializable;
import java.util.Objects;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ServerResponseEntity<T> implements Serializable {
private static final Logger log = LoggerFactory.getLogger(ServerResponseEntity.class);
private String code;
private String msg;
private T data;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
public boolean isSuccess() {
return Objects.equals(ResponseEnum.OK.value(), this.code);
}
@Override
public String toString() {
return "ServerResponseEntity{" + "code=" + code + ", msg='" + msg + '\'' + ", data=" + data + '}';
}
public static <T> ServerResponseEntity<T> success(T data) {
ServerResponseEntity<T> serverResponseEntity = new ServerResponseEntity<>();
serverResponseEntity.setData(data);
serverResponseEntity.setCode(ResponseEnum.OK.value());
return serverResponseEntity;
}
public static <T> ServerResponseEntity<T> success() {
ServerResponseEntity<T> serverResponseEntity = new ServerResponseEntity<>();
serverResponseEntity.setCode(ResponseEnum.OK.value());
serverResponseEntity.setMsg(ResponseEnum.OK.getMsg());
return serverResponseEntity;
}
public static <T> ServerResponseEntity<T> showFailMsg(String msg) {
log.error(msg);
ServerResponseEntity<T> serverResponseEntity = new ServerResponseEntity<>();
serverResponseEntity.setMsg(msg);
serverResponseEntity.setCode(ResponseEnum.SHOW_FAIL.value());
return serverResponseEntity;
}
public static <T> ServerResponseEntity<T> fail(ResponseEnum responseEnum) {
log.error(responseEnum.toString());
ServerResponseEntity<T> serverResponseEntity = new ServerResponseEntity<>();
serverResponseEntity.setMsg(responseEnum.getMsg());
serverResponseEntity.setCode(responseEnum.value());
return serverResponseEntity;
}
public static <T> ServerResponseEntity<T> fail(ResponseEnum responseEnum, T data) {
log.error(responseEnum.toString());
ServerResponseEntity<T> serverResponseEntity = new ServerResponseEntity<>();
serverResponseEntity.setMsg(responseEnum.getMsg());
serverResponseEntity.setCode(responseEnum.value());
serverResponseEntity.setData(data);
return serverResponseEntity;
}
public static <T> ServerResponseEntity<T> transform(ServerResponseEntity<?> oldServerResponseEntity) {
ServerResponseEntity<T> serverResponseEntity = new ServerResponseEntity<>();
serverResponseEntity.setMsg(oldServerResponseEntity.getMsg());
serverResponseEntity.setCode(oldServerResponseEntity.getCode());
log.error(serverResponseEntity.toString());
return serverResponseEntity;
}
}