windows下安装minio并实现文件上传
一 Minio简介
MinIO 是一个基于Apache License v2.0开源协议的对象存储服务。它兼容亚马逊S3云存储服务接口,非常适合于存储大容量非结构化的数据,例如图片、视频、日志文件、备份数据和容器/虚拟机镜像等,而一个对象文件可以是任意大小,从几kb到最大5T不等。
MinIO是一个非常轻量的服务,可以很简单的和其他应用的结合,类似 NodeJS, Redis 或者 MySQL,做二次开发工作。
二 linux下安装(详见以下连接文档)
Linux下安装Miniohttps://blog.csdn.net/ytyDaMoTou/article/details/125732317
三 Minio常见面试题
暂无整理...待整理
四 springboot集成minio
1 导入pom
<dependency> <groupId>io.minio</groupId> <artifactId>minio</artifactId> <version>8.0.3</version> </dependency>
2 配置文件增加配置‘
minio: #注意此处是https,由于后续讨论协议问题因此提前修改,不需要的可自行修改为http endpoint: http://172.168.1.209:9005 accesskey: MzAFXSMcoLUMshUJTqlQ #你的服务账号 secretkey: AySFiAdnzQ4LKGxqImMjeMNFrb9b9IeSzAQWpw7y #你的服务密码 buckname: cjfile #文件夹server: port: 9999 servlet: context-path: /api multipart: max-file-size: 200MB max-request-size: 200MB
3 增加代码
MinioInfo.java代码
package com.example.ytyproject.entity.vo;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Data
@Component
@ConfigurationProperties(prefix = "minio")
public class MinioInfo {
private String endpoint;
private String accesskey;
private String secretkey;
private String buckname;
}
package com.example.ytyproject.config;
import com.example.ytyproject.entity.vo.MinioInfo;
import io.minio.MinioClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
@Configuration
@EnableConfigurationProperties(MinioInfo.class)
public class MinioConfig {
@Autowired
private MinioInfo minioInfo;
/**
* 获取 MinioClient
*/
@Bean
public MinioClient minioClient() throws NoSuchAlgorithmException, KeyManagementException {
return MinioClient.builder().endpoint(minioInfo.getEndpoint())
.credentials(minioInfo.getAccesskey(),minioInfo.getSecretkey())
.build();
}
}
package com.example.ytyproject.component;
import com.example.ytyproject.config.exception.AppException;
import com.example.ytyproject.entity.vo.MinioInfo;
import io.minio.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.UUID;
/**
* minio文件管理
*/
@Slf4j
@Component
public class MinioComponent {
@Autowired
private MinioClient minioClient;
@Autowired
private MinioInfo minioInfo;
/**
* 上传文件
* @param file 文件
* @return 文件路径
*/
public String uploadFile(MultipartFile file, String filePath){
if (null == file || 0 == file.getSize()){
throw new AppException("上传文件不能为空!");
}
try {
//判断是否存在
createBucket();
//原文件名
String originalFilename = file.getOriginalFilename();
// 修改文件名称
String fileName = filePath + UUID.randomUUID().toString().replace("-", "") + originalFilename.substring(originalFilename.indexOf("."));
minioClient.putObject(PutObjectArgs.builder().bucket(minioInfo.getBuckname())
.object(fileName)
.stream(file.getInputStream(), file.getSize(), -1)
.contentType(file.getContentType()).build());
return minioInfo.getEndpoint() + "/" + minioInfo.getBuckname() + "/" + fileName;
} catch (Exception e){
log.error("上传失败::", e);
throw new AppException("上传失败!");
}
}
public void createBucket() throws Exception{
//如果不存在就创建
if (!minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioInfo.getBuckname()).build())) {
minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioInfo.getBuckname()).build());
}
}
/**
* 通过字节流上传
* @param imageFullPath
* @param bucketName
* @param imageData
* @return
*/
public String uploadImage(String imageFullPath,
String bucketName,
byte[] imageData){
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(imageData);
try {
//判断是否存在
createBucket();
minioClient.putObject(PutObjectArgs.builder().bucket(bucketName).object(imageFullPath)
.stream(byteArrayInputStream,byteArrayInputStream.available(),-1)
.contentType(".jpg")
.build());
return minioInfo.getEndpoint()+"/"+bucketName+"/"+imageFullPath;
}catch (Exception e){
log.error("上传失败:{}",e.getMessage());
}
log.error("msg","上传失败");
return null;
}
/**
* 删除文件
* @param bucketName
* @param fileName
* @return
*/
public int removeFile(String bucketName,String fileName){
try {
//判断桶是否存在
boolean res = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
if (res) {
//删除文件
minioClient.removeObject(RemoveObjectArgs.builder().bucket(bucketName).object(fileName).build());
}
} catch (Exception e) {
System.out.println("删除文件失败");
e.printStackTrace();
return 1;
}
System.out.println("删除文件成功");
return 0;
}
/**
* 下载文件
* @param fileName
* @param bucketName
* @param response
*/
public void fileDownload(String fileName,
String bucketName,
HttpServletResponse response) {
InputStream inputStream = null;
OutputStream outputStream = null;
try {
if (StringUtils.isBlank(fileName)) {
response.setHeader("Content-type", "text/html;charset=UTF-8");
String data = "文件下载失败";
OutputStream ps = response.getOutputStream();
ps.write(data.getBytes("UTF-8"));
return;
}
outputStream = response.getOutputStream();
// 获取文件对象
inputStream =minioClient.getObject(GetObjectArgs.builder().bucket(bucketName).object(fileName).build());
byte buf[] = new byte[1024];
int length = 0;
response.reset();
response.setHeader("Content-Disposition", "attachment;filename=" +
URLEncoder.encode(fileName.substring(fileName.lastIndexOf("/") + 1), "UTF-8"));
response.setContentType("application/octet-stream");
response.setCharacterEncoding("UTF-8");
// 输出文件
while ((length = inputStream.read(buf)) > 0) {
outputStream.write(buf, 0, length);
}
System.out.println("下载成功");
inputStream.close();
} catch (Throwable ex) {
response.setHeader("Content-type", "text/html;charset=UTF-8");
String data = "文件下载失败";
try {
OutputStream ps = response.getOutputStream();
ps.write(data.getBytes("UTF-8"));
}catch (IOException e){
e.printStackTrace();
}
} finally {
try {
outputStream.close();
if (inputStream != null) {
inputStream.close();
}}catch (IOException e){
e.printStackTrace();
}
}
}
}
入口代码
package com.example.ytyproject.controller;
import com.alibaba.fastjson.JSONObject;
import com.example.ytyproject.component.MinioComponent;
import com.example.ytyproject.entity.vo.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
@RestController
@RequestMapping("/file/minio")
public class FileController {
@Autowired
private MinioComponent minioComponent;
@PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public R uploadByMinio(@RequestParam(name = "file") MultipartFile file) {
//返回存储路径
String path = minioComponent.uploadFile(file, "admin/test/");
return R.ok(path);
}
}