pom.xml
<dependency>
<groupId>io.minio</groupId>
<artifactId>minio</artifactId>
<version>7.0.1</version>
</dependency>
编辑配置文件 application.yml
minio:
endpoint: http://192.168.3.40:9000
accesskey: minio
secretKey: 123456
bucketName: wanhua
@Configuration
@EnableConfigurationProperties(MinioPro.class)
public class MinioConfiguration {
@Resource
private MinioPro minioPro;
/**
* 初始化 MinIO 客户端
*/
@Bean
public MinioClient minioClient() throws InvalidPortException, InvalidEndpointException {
return new MinioClient(minioPro.getEndpoint(), minioPro.getAccesskey(), minioPro.getSecretKey());
}
}
Bean
@Data
@ConfigurationProperties(prefix = "minio")
public class MinioPro {
/**
* 端点
*/
private String endpoint;
/**
* 用户名
*/
private String accesskey;
/**
* 密码
*/
private String secretKey;
/**
* 桶名称
*/
private String bucketName;
实现层的Base64上传方法
public String uploadImg(Oss oss) {
//oss是前端传来的base64对象,第一行代码将获取对象中的base64字符串
try {
byte[] decode = Base64.getDecoder().decode(oss.getIcon());
InputStream byteArrayInputStream = new ByteArrayInputStream(decode);
String bucketName = minio.getBucketName();
boolean bucketExists = minioClient.bucketExists(bucketName);
if (!bucketExists) {
minioClient.makeBucket(bucketName);
}
// 生成文件名称
String nameSuffix = UUID.randomUUID().toString() + ".jpg";
String url = "/show?fileName=" +nameSuffix;
// 上传配置
PutObjectOptions options = new PutObjectOptions(byteArrayInputStream.available(), PutObjectOptions.MIN_MULTIPART_SIZE);
options.setContentType("image/jpeg");
minioClient.putObject(bucketName, nameSuffix, byteArrayInputStream, options);
return url;
} catch (Exception e) {
log.error("上传文件失败", e.getMessage());
return "上传文件失败";
}
}
页面展示方法
public void show(String fileName, HttpServletResponse response) {
InputStream in = null;
OutputStream out = null;
try {
MinioClient minioClient = new MinioClient(minio.getEndpoint(), minio.getAccesskey(), minio.getSecretKey());
in=minioClient.getObject(minio.getBucketName(), fileName);
int length = 0;
byte buf[] = new byte[1024];
out = response.getOutputStream();
response.reset();
//Content-disposition 是 MIME 协议的扩展,MIME 协议指示 MIME 用户代理如何显 示附加的文件。
// Content-disposition其实可以控制用户请求所得的内容存为一个文件的时候提供一个默认的文件名,
// 文件直接在浏览器上显示或者在访问时弹出文件下载对话框。
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
response.setCharacterEncoding("utf-8");
while ((length = in.read(buf))>0) {
out.write(buf,0, length);
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}