前提:安装MinIO服务
1.Maven配置
Springboot2.6.3
<!--minio 8.2.2没有报依赖异常 新版报异常-->
<dependency>
<groupId>io.minio</groupId>
<artifactId>minio</artifactId>
<version>8.2.2</version>
</dependency>
2.yml配置
添加对应的配置
minio:
#api地址
endpoint: http://127.0.0.1:9000
#密钥
accessKey: minioadmin
#密钥
secretKey: minioadmin
#文件资源桶(必须要在控制台创建相同的桶)
bucketName: default
登录MinIO控制台,创建“桶”,名字要相同
要是没有创建桶,会有异常 (桶没找到)
3.代码
多余配置为swagger、返回类、等可忽略替换
3.1.controller
package com.cn.controller;
import com.alibaba.fastjson2.JSON;
import com.cn.common.AjaxResult;
import com.cn.common.HttpStatus;
import com.cn.minio.MinIOUtil;
import com.cn.util.ServletUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
/**
* @program: toolbox
* @description
* @date 2023/4/23
*/
@Api(value = "MinioController", tags = {"MinIO"})
@RestController
@Slf4j
public class MinioController {
@Autowired
private MinIOUtil minioUtil;
@ApiOperation("上传")
@PostMapping("/upload")
public AjaxResult upload(@RequestPart MultipartFile file) {
String filePath;
try {
filePath = minioUtil.putObject(file);
} catch (Exception e) {
e.printStackTrace();
return AjaxResult.error("上传失败");
}
return AjaxResult.success(filePath);
}
@ApiOperation("下载")
@GetMapping("/download")
public void download(HttpServletResponse response, @ApiParam(name = "filepath", value = "文件路径", required = true) String filepath) {
try {
minioUtil.getObject(response, filepath);
} catch (Exception e) {
e.printStackTrace();
log.error("下载失败", e);
response.reset();
AjaxResult result = new AjaxResult(HttpStatus.ERROR, e.getMessage());
String json = JSON.toJSONString(result);
ServletUtils.renderString(response, json);
}
}
}
3.2.MinIoConfig
package com.cn.minio;
import io.minio.MinioClient;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @program: toolbox
* @description
* @date 2023/4/24
*/
@Data
@Configuration
@ConfigurationProperties(prefix="minio")
public class MinIoConfig {
/**
* 访问密钥
*/
@Value("${minio.accessKey}")
private String accessKey;
/**
* 密钥
*/
@Value("${minio.secretKey}")
private String secretKey;
/**
* 访问api Url
*/
@Value("${minio.endpoint}")
private String endpoint;
/**
* 捅名称
*/
@Value("${minio.bucketName}")
private String bucketName;
/**
* 创建MinIo客户端
*
* @return
*/
@Bean
public MinioClient minioClient() {
return MinioClient.builder()
.endpoint(endpoint)
.credentials(accessKey, secretKey)
.build();
}
}
3.3.MinIOUtil
package com.cn.minio;
import io.minio.GetObjectArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.errors.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* @program: toolbox
* @description
* @date 2023/4/24
*/
@Component
public class MinIOUtil {
@Autowired
private MinioClient minioClient;
/**
* 捅名称
*/
@Value("${minio.bucketName}")
private String bucketName;
/**
* putObject上传文件
*
* @param file 文件
* @return filePath
*/
public String putObject(MultipartFile file) throws IOException, ServerException, InsufficientDataException, InternalException, InvalidResponseException, InvalidKeyException, NoSuchAlgorithmException, XmlParserException, ErrorResponseException {
//文件名
String originalFilename = file.getOriginalFilename();
//文件流
InputStream inputStream = file.getInputStream();
//文件大小
long size = file.getSize();
//文件路径
String filePath = createFilePath(originalFilename);
//存储方法 putObject
minioClient.putObject(PutObjectArgs.builder()
.bucket(bucketName)
.object(filePath)
.stream(inputStream, size, -1)
.contentType(file.getContentType())
.build());
return filePath;
}
/**
* 下载文件
*
* @param filePath 文件路径
*/
public void getObject(HttpServletResponse httpServletResponse, String filePath) throws IOException, InvalidKeyException, InvalidResponseException, InsufficientDataException, NoSuchAlgorithmException, ServerException, InternalException, XmlParserException, ErrorResponseException {
String fileName = getFileName(filePath);
InputStream inputStream = minioClient.getObject(GetObjectArgs.builder()
.bucket(bucketName)
.object(filePath)
.build());
downloadFile(httpServletResponse, inputStream, fileName);
}
/**
* 获取文件路径
*
* @param originalFilename 原始文件名称
* @return FilePath
*/
public String createFilePath(String originalFilename) {
return new SimpleDateFormat("yyyy/MM/dd").format(new Date()) + "/" + originalFilename;
}
/**
* 根据文件路径获取文件名称
*
* @param filePath 文件路径
* @return 文件名
*/
public String getFileName(String filePath) {
String[] split = StringUtils.split(filePath, "/");
return split[split.length - 1];
}
/**
* 下载文件
*
* @param httpServletResponse httpServletResponse
* @param inputStream inputStream
* @param fileName 文件名
* @throws IOException IOException
*/
public void downloadFile(HttpServletResponse httpServletResponse, InputStream inputStream, String fileName) throws IOException {
//设置响应头信息,告诉前端浏览器下载文件
httpServletResponse.setContentType("application/octet-stream;charset=UTF-8");
httpServletResponse.setCharacterEncoding("UTF-8");
httpServletResponse.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
//获取输出流进行写入数据
OutputStream outputStream = httpServletResponse.getOutputStream();
// 将输入流复制到输出流
byte[] buffer = new byte[4096];
int bytesRead = -1;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
// 关闭流资源
inputStream.close();
outputStream.close();
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/192753.html