1、添加依赖
<!-- https://mvnrepository.com/artifact/io.minio/minio -->
<dependency>
<groupId>io.minio</groupId>
<artifactId>minio</artifactId>
<version>8.4.0</version>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.10.0</version>
</dependency>
2、yml文件加入配置
minio:
endpoint: http://192.168.0.117:9000
accessKey: admin
secretKey: password
bucketName: test
3、后端代码编写
链接配置类
package com.wxf.config;
import io.minio.MinioClient;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @Author: anshen
* @Date: 2023/5/23 16:42
*/
@Configuration
@Slf4j
@Data
public class MinioClientConfig {
@Value("${minio.endpoint}")
private String endpoint;
@Value("${minio.accessKey}")
private String accessKey;
@Value("${minio.secretKey}")
private String secretKey;
@Value("${minio.bucketName}")
private String bucketName;
@Bean
public MinioClient minioClient() {
log.info("endpoint={} , accessKey={} ,secretKey={}", endpoint, accessKey, secretKey);
return MinioClient.builder().credentials(accessKey, secretKey).endpoint(endpoint).build();
}
}
先写测试类文件
package com.wxf.util;
import io.minio.*;
import io.minio.errors.MinioException;
import io.minio.http.Method;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
/**
* @Author: anshen
* @Date: 2022/12/7 18:12
*/
public class FileUploader {
public static void main(String[] args)
throws IOException, NoSuchAlgorithmException, InvalidKeyException {
try {
// Create a minioClient with the MinIO server playground, its access key and secret key.
//使用MinIO服务器游乐场、其访问密钥和密钥创建一个从属客户端。
/* MinioClient minioClient = MinioClient.builder()
.endpoint("https://play.min.io")
.credentials("Q3AM3UQ867SPQQA43P2F", "zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG")
.build();*/
MinioClient minioClient = MinioClient.builder()
.endpoint("http://192.168.0.39",9000,false)
.credentials("yuHzPYjauxCbPv98", "u6qKhewjk75rXlpZXYvslZkNFdAhC30x")
.build();
// Make 'asiatrip' bucket if not exist.
// 如果不存在,则创建“asiatrip”桶。
boolean found =
////minioClient.bucketExists(BucketExistsArgs.builder().bucket("asiatrip").build());
minioClient.bucketExists(BucketExistsArgs.builder().bucket("test").build());
if (!found) {
// Make a new bucket called 'asiatrip'.
// 制作一个名为“asiatrip”的新桶。
////minioClient.makeBucket(MakeBucketArgs.builder().bucket("asiatrip").build());
minioClient.makeBucket(MakeBucketArgs.builder().bucket("test").build());
} else {
System.out.println("Bucket 'test' already exists.");
}
// Upload '/home/user/Photos/asiaphotos.zip' as object name 'asiaphotos-2015.zip' to bucket
//上传'/home/user/Photos/asiaphotos。zip'作为对象名'asiaphotos-2015.zip'到桶
// 'asiatrip'.
/*minioClient.uploadObject(
UploadObjectArgs.builder()
.bucket("test")
.object("20220215004159801.jpeg")
.filename("D:\\workspace\\LLY\\零零易喆啡图\\img\\20220215004159801.jpeg")
.build());*/
System.out.println(
"'D:\\workspace\\LLY\\零零易喆啡图\\img\\20220125171321089.jpeg' is successfully uploaded as "
+ "object 'demo.htm' to bucket 'test'.");
/*Map<String, String> reqParams = new HashMap<String, String>();
reqParams.put("response-content-type", "application/json");
String url = minioClient.getPresignedObjectUrl(GetPresignedObjectUrlArgs.builder()
.method(Method.GET)
.bucket("test")
.object("20220125171321089")
.expiry(2, TimeUnit.HOURS)
.extraQueryParams(reqParams)
.build());
System.out.println(url);*/
String url =
minioClient.getPresignedObjectUrl(
GetPresignedObjectUrlArgs.builder()
.method(Method.GET)
.bucket("test")
.object("2.jpeg")
.build());
System.out.println(url);
} catch (MinioException e) {
System.out.println("Error occurred: " + e);
System.out.println("HTTP trace: " + e.httpTrace());
}
}
}
编写文件工具类
package com.wxf.util;
import io.minio.*;
import io.minio.errors.MinioException;
import io.minio.http.Method;
import io.minio.messages.Bucket;
import lombok.SneakyThrows;
import org.apache.commons.compress.utils.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeUnit;
/**
* @Author: anshen
* @Date: 2023/5/23 16:45
*/
@Component
public class MinioUtils {
@Autowired
private MinioClient minioClient;
/**
* 判断桶是否存在
*/
@SneakyThrows(Exception.class)
public boolean bucketExists(String bucketName) {
return minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
}
/**
* 创建桶
* @param bucketName
* 获取全部的桶 minioClient.listBuckets();
*/
@SneakyThrows(Exception.class)
public void createBucket(String bucketName) {
if (!minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build())) {
minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
}
}
/**
* 根据bucketName获取信息
* @param bucketName bucket名称
*/
@SneakyThrows(Exception.class)
public Optional<Bucket> getBucket(String bucketName) {
return minioClient.listBuckets().stream().filter(b -> b.name().equals(bucketName)).findFirst();
}
/**
* 根据bucketName删除信息
* @param bucketName bucket名称
*/
@SneakyThrows(Exception.class)
public void removeBucket(String bucketName) {
minioClient.removeBucket(RemoveBucketArgs.builder().bucket(bucketName).build());
}
/**
* 获取文件流
* @param bucketName bucket名称
* @param objectName 文件名称
* @return 二进制流
*/
@SneakyThrows(Exception.class)
public InputStream getObject(String bucketName, String objectName) {
return minioClient.getObject(GetObjectArgs.builder().bucket(bucketName).object(objectName).build());
}
/**
* 上传本地文件
* @param bucketName 存储桶
* @param objectName 对象名称
* @param fileName 本地文件路径
*/
@SneakyThrows(Exception.class)
public ObjectWriteResponse putObject(String bucketName, String objectName, String fileName) {
if(!bucketExists(bucketName)){
createBucket(bucketName);
}
return minioClient.uploadObject(UploadObjectArgs.builder().bucket(bucketName).object(objectName).filename(fileName).build());
}
/**
* 通过流上传文件
* @param bucketName 存储桶
* @param objectName 文件对象
* @param inputStream 文件流
*/
@SneakyThrows(Exception.class)
public ObjectWriteResponse putObject(String bucketName, String objectName, InputStream inputStream) {
if(!bucketExists(bucketName)){
createBucket(bucketName);
}
return minioClient.putObject(PutObjectArgs.builder().bucket(bucketName).object(objectName).stream(inputStream, inputStream.available(), -1).build());
}
public boolean savefileToMinByPath(String bucketName,String objectName,String fileName)
throws IOException, NoSuchAlgorithmException, InvalidKeyException {
try {
// Make 'asiatrip' bucket if not exist.
// 如果不存在,则创建“asiatrip”桶。
boolean found =
////minioClient.bucketExists(BucketExistsArgs.builder().bucket("asiatrip").build());
minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
if (!found) {
// Make a new bucket called 'asiatrip'.
// 制作一个名为“asiatrip”的新桶。
////minioClient.makeBucket(MakeBucketArgs.builder().bucket("asiatrip").build());
minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
} else {
System.out.println("Bucket "+bucketName+" already exists.");
}
// Upload '/home/user/Photos/asiaphotos.zip' as object name 'asiaphotos-2015.zip' to bucket
//上传'/home/user/Photos/asiaphotos。zip'作为对象名'asiaphotos-2015.zip'到桶
// 'asiatrip'.
minioClient.uploadObject(
UploadObjectArgs.builder()
.bucket(bucketName)
.object(objectName)
.filename(fileName)
.build());
return true;
} catch (MinioException e) {
System.out.println("Error occurred: " + e);
System.out.println("HTTP trace: " + e.httpTrace());
return false;
}
}
public boolean savefileToMinByBase64(String bucketName,String objectName,String fileName)
throws IOException, NoSuchAlgorithmException, InvalidKeyException {
try {
boolean found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
if (!found) {
minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
} else {
System.out.println("Bucket "+bucketName+" already exists.");
}
BASE64Decoder decoder = new BASE64Decoder();
byte[] bytes1 = decoder.decodeBuffer(fileName);
ByteArrayInputStream stream = new ByteArrayInputStream(bytes1);
minioClient.putObject( PutObjectArgs.builder() .bucket(bucketName) .object(objectName) .stream(stream, stream.available(), -1).build());
return true;
} catch (MinioException e) {
System.out.println("Error occurred: " + e);
System.out.println("HTTP trace: " + e.httpTrace());
return false;
}catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 单个文件上传
* @param bucketName
* @param multipartFile
* @return
*/
@SneakyThrows(Exception.class)
public String uploadFileSingle(String bucketName,MultipartFile multipartFile ) {
if(!bucketExists(bucketName)){
createBucket(bucketName);
}
String fileName = multipartFile.getOriginalFilename();
String[] split = fileName.split("\\.");
if (split.length > 1) {
fileName = split[0] + "_" + System.currentTimeMillis() + "." + split[1];
} else {
fileName = fileName + System.currentTimeMillis();
}
InputStream in = null;
try {
in = multipartFile.getInputStream();
minioClient.putObject(PutObjectArgs.builder().bucket(bucketName).object(fileName).stream(in, in.available(), -1).contentType(multipartFile.getContentType()).build());
} catch (Exception e) {
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return getUploadObjectUrlByEndTime(bucketName,fileName, 7*24*60*60);
}
/**
* description: 上传文件
* @param multipartFile
* @return: java.lang.String
*/
public List<String> uploadFileBatch(String bucketName, MultipartFile[] multipartFile) {
if(!bucketExists(bucketName)){
createBucket(bucketName);
}
List<String> names = new ArrayList<>();
for (MultipartFile file : multipartFile) {
try {
String fileName = file.getOriginalFilename();
uploadFileSingle(bucketName,file);
names.add(fileName);
}catch (Exception e){
e.printStackTrace();
}
}
return names;
}
/**
* 获取文件外链
* @param bucketName bucket名称
* @param objectName 文件名称
* @param expires 过期时间 <=7 秒级
* @return url
*/
@SneakyThrows(Exception.class)
public String getUploadObjectUrlByEndTime(String bucketName, String objectName, Integer expires) {
return minioClient.getPresignedObjectUrl(GetPresignedObjectUrlArgs.builder().method(Method.PUT).bucket(bucketName).object(objectName).expiry(expires).build());
}
/**
* 获取文件外链
* @param bucketName bucket名称
* @param objectName 文件名称
* @param expires 过期时间 <=7 秒级
* @return url
*/
@SneakyThrows(Exception.class)
public String getUploadObjectUrlSpecifyIntervalByEndTime(String bucketName, String objectName, Integer expires, TimeUnit timeUtil) {
return minioClient.getPresignedObjectUrl(GetPresignedObjectUrlArgs.builder().method(Method.PUT).bucket(bucketName).object(objectName).expiry(expires,timeUtil).build());
}
/**
* 获取文件外链
* @param bucketName bucket名称
* @param objectName 文件名称
* @return url
*/
@SneakyThrows(Exception.class)
public String getUploadObjectUrl(String bucketName, String objectName) {
return minioClient.getPresignedObjectUrl(GetPresignedObjectUrlArgs.builder().method(Method.GET).bucket(bucketName).object(objectName).build());
}
/**
* 下载文件
* bucketName:桶名
* @param fileName: 文件名
*/
@SneakyThrows(Exception.class)
public void download(String bucketName,String fileName, HttpServletResponse response) {
// 获取对象的元数据
StatObjectResponse stat = minioClient.statObject(StatObjectArgs.builder().bucket(bucketName).object(fileName).build());
response.setContentType(stat.contentType());
response.setCharacterEncoding("UTF-8");
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
InputStream is = minioClient.getObject(GetObjectArgs.builder().bucket(bucketName).object(fileName).build());
IOUtils.copy(is, response.getOutputStream());
is.close();
}
}
文件上传接口
@SneakyThrows
@PostMapping("/uploadFile")
@ResponseBody
public String uploadFile(@RequestParam("file")MultipartFile multipartFile ){
log.info("uploadFile ---- ----- start ");
String imgPath = minioUtils.uploadFileSingle(bucketName, multipartFile);
log.info("uploadFile ---- ----- end {}",imgPath);
return imgPath;
}
前端测试代码
前端代码编写
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>测试Minio上传文件</title>
<style>
a.upload-img {
width: 165px;
display: inline-block;
margin-bottom: 10px;
text-align: center;
height: 37px;
line-height: 37px;
font-size: 14px;
color: #FFFFFF;
background-color: #f38e81;
border-radius: 3px;
text-decoration: none;
cursor: pointer;
border: 0px #fff solid;
box-shadow: 0px 0px 5px #B0B0B0;
}
</style>
</head>
<body>
<div style="width: 100%;flex: auto">
<form id="img-form">
<a href="void(0)" class="upload-img"><label for="inputImage">上传图像</label> </a>
<input onchange="doUpload()" type="file" name="file" id="inputImage" accept="image/*"/>
</form>
<img height="120px" style="margin-left: 20px" >
</div>
let doUpload=()=>{
console.log("1---> start upload ");
let file = document.getElementById("inputImage").files[0];
if (/^image\/\w+$/.test(file.type)) {
let form = document.getElementById("img-form");
let formData = new FormData(form);
let oReq = new XMLHttpRequest();
oReq.open("POST", "http://127.0.0.1:9055/uploadFile", true);
oReq.send(formData);
oReq. function(oEvent) {
if(oReq.status == 200) {
alert("Uploaded Success");
console.log("1---> end upload ",oReq.response)
}
}
}
}
</body>
</html>
注意:本文归作者所有,未经作者允许,不得转载