创建buckets
创建service accounts
java上传文件
maven依赖:
<dependency>
<groupId>io.minio</groupId>
<artifactId>minio</artifactId>
<version>7.0.2</version>
</dependency>
java代码:
package org.example.controller;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.NoSuchAlgorithmException;
import java.security.InvalidKeyException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
import io.minio.PutObjectOptions;
import org.xmlpull.v1.XmlPullParserException;
import io.minio.MinioClient;
import io.minio.errors.MinioException;
public class FileUploader {
public static void main(String[] args) throws NoSuchAlgorithmException, IOException, InvalidKeyException, XmlPullParserException {
uploadFile();
}
private static void uploadFile() throws InvalidKeyException, IOException, NoSuchAlgorithmException {
try {
//你的endpoint,本机可以不变
String endpoint = "http://ip:9000";
//你的accessKey
String accessKey = "Ftl430el5M7IMKyp";
//你的sercetKey
String secretKey = "ek1IHUaH1o3EeIlcO5NwN9RLAlomvCCn";
//你的bucket
String bucketName = "test";
// 使用MinIO服务的URL,端口,Access key和Secret key创建一个MinioClient对象
MinioClient minioClient = new MinioClient(endpoint, accessKey, secretKey);
// 检查存储桶是否已经存在
boolean isExist = minioClient.bucketExists(bucketName);
if (isExist) {
System.out.println("Bucket already exists.");
} else {
// 创建一个名为asiatrip的存储桶,用于存储照片的zip文件。
minioClient.makeBucket(bucketName);
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd/");
String date = sdf.format(new Date());
//找一个你电脑上图片的绝对路径,最好是PNG图片
File file = new File("D:\\data\\hei.png");
long size = file.length();
String fileName = file.getName();
InputStream is = new FileInputStream(file);
//将待上传的文件的路径设置成 年/月/日/uuid+file01.png
//你也可以自定义上传文件的路径,这样设置是为了更好的管理
String uuid = UUID.randomUUID().toString().replace("-", "").substring(0, 6);
String fileUploadPath = date + uuid + "file01" + fileName.substring(fileName.lastIndexOf("."));
PutObjectOptions options = new PutObjectOptions(size, -1);
//设置图片的contentType,如果不是PNG图片就自行修改对应的contentType,这样做的目的是为了上传之后访问图片时可以在浏览器预览而不用下载,当然也可以注释这行代码
options.setContentType("image/png");
minioClient.putObject(bucketName, fileUploadPath, is, options);
System.out.println(file.getAbsolutePath() + "is successfully uploaded as 【" + fileUploadPath + "】 to 【" + bucketName + "】bucket.");
} catch (MinioException e) {
System.out.println("Error occurred: " + e);
}
}
}
预览文件:
修改Buckets权限
浏览器访问:http://ip:9000/test/2022/08/08/9a6c36file01.png