当前位置:   article > 正文

MinIO文件服务器的安装使用_minio安装

minio安装

什么是MinIO

MinIO 是一款高性能、分布式的对象存储系统

MinIO提供高性能、S3兼容的对象存储

目录

一、安装步骤

1.1 连接服务器(此处为linux系统)

1.2 使用命令在root目录下创建minio文件夹,打开minio文件夹,下载minio

1.3 下载完成后会在当前目录下出现一个minio目录,为该文件添加可执行权限

1.4 创建minio文件存储目录及日志目录

1.5 在 /root/minio/目录下,新建一个run.sh并编辑以下内容,使用命令vim run.sh,然后将以下内容保存到run.sh。注:用户名和密码自己设置

1.6 为其赋予执行权限chmod u+x run.sh

1.7 启动minio并查看日志

1.8 访问其中的http://192.169.1.6:9002,使用5中配置的用户名密码登录

 1.9 创建Buckets(桶)

1.10 创建访问密钥并保存。注:springboot整合需要用到

 二、使用步骤

2.1 项目引入依赖

2.2 application.yml文件里配置minio。注:minio配置信息需改为自身的

2.3 创建minio配置类和工具类

2.4 创建一个数据表,用于保存上传到minio的文件的信息

2.5 使用代码自动生成器生成entity、controller、service、mapper。

2.6 创建minio上传、删除接口

2.7 封装上传返回数据MinioResponseDTO对象

2.8 测试


一、安装步骤

1.1 连接服务器(此处为linux系统)

1.2 使用命令在root目录下创建minio文件夹,打开minio文件夹,下载minio

  1. cd
  2. mkdir minio
  3. cd minio
  4. wget https://dl.min.io/server/minio/release/linux-amd64/minio

1.3 下载完成后会在当前目录下出现一个minio目录,为该文件添加可执行权限

chmod +x minio

1.4 创建minio文件存储目录及日志目录

  1. # 创建minio文件存储目录及日志目录
  2. mkdir -p /root/data/minio;
  3. mkdir -p /root/logs/minio;

1.5 在 /root/minio/目录下,新建一个run.sh并编辑以下内容,使用命令vim run.sh,然后将以下内容保存到run.sh。注:用户名和密码自己设置

  1. #!/bin/bash
  2. export MINIO_ROOT_USER=minio-username
  3. export MINIO_ROOT_PASSWORD=minio-password
  4. # nohup启动服务 指定文件存放路径 /root/data 还有设置日志文件路径 /root/minio/log
  5. nohup ./minio server --address :9002 --console-address :9001 /root/data/minio > /root/logs/minio/minio.log 2>&1 &

1.6 为其赋予执行权限chmod u+x run.sh

chmod u+x run.sh

1.7 启动minio并查看日志

  1. # 启动minio服务
  2. bash run.sh
  3. # 查看日志
  4. tail -200f /root/logs/minio/minio.log

 出现以下内容即安装成功

1.8 访问其中的http://192.169.1.6:9002,使用5中配置的用户名密码登录

 1.9 创建Buckets(桶)

1.10 创建访问密钥并保存。注:springboot整合需要用到

 二、使用步骤

2.1 项目引入依赖

  1. <dependencies>
  2. <dependency>
  3. <groupId>io.minio</groupId>
  4. <artifactId>minio</artifactId>
  5. <version>7.1.0</version>
  6. </dependency>
  7. </dependencies>

2.2 application.yml文件里配置minio。注:minio配置信息需改为自身的

  1. minio:
  2. endpoint: http://192.168.1.6:9002
  3. # 安装步骤10中创建的访问密钥
  4. accessKey: ***************
  5. secretKey: ********************
  6. # 安装步骤9中创建的bckets名字
  7. bucketName: test
  8. secure: false
  9. spring:
  10. mvc:
  11. hiddenmethod:
  12. filter:
  13. enabled: true
  14. # 设置文件上传大小限制
  15. servlet:
  16. multipart:
  17. max-file-size: 100MB
  18. max-request-size: 150MB

2.3 创建minio配置类和工具类

配置类:

  1. import io.minio.MinioClient;
  2. import io.minio.errors.InvalidPortException;
  3. import lombok.Data;
  4. import org.springframework.boot.context.properties.ConfigurationProperties;
  5. import org.springframework.context.annotation.Bean;
  6. import org.springframework.context.annotation.Configuration;
  7. import org.springframework.stereotype.Component;
  8. /**
  9. * @author Lannibar
  10. * @date: 2023-5-17
  11. * @Description minio配置
  12. */
  13. @Configuration
  14. @Component
  15. @ConfigurationProperties(prefix = "minio")
  16. @Data
  17. public class MinioConfig {
  18. private String endpoint;
  19. private int port;
  20. private String accessKey;
  21. private String secretKey;
  22. private Boolean secure;
  23. private String bucketName;
  24. @Bean
  25. public MinioClient getMinioClient() throws InvalidPortException {
  26. MinioClient minioClient = MinioClient.builder().endpoint(endpoint)
  27. .credentials(accessKey, secretKey)
  28. .build();
  29. return minioClient;
  30. }
  31. }

工具类:

  1. package com.xiaomifeng.minio.util;
  2. import io.minio.*;
  3. import io.minio.errors.*;
  4. import io.minio.http.Method;
  5. import io.minio.messages.Bucket;
  6. import io.minio.messages.DeleteError;
  7. import io.minio.messages.DeleteObject;
  8. import io.minio.messages.Item;
  9. import lombok.extern.slf4j.Slf4j;
  10. import org.apache.commons.lang.StringUtils;
  11. import org.springframework.beans.factory.annotation.Autowired;
  12. import org.springframework.stereotype.Component;
  13. import org.springframework.web.multipart.MultipartFile;
  14. import javax.servlet.ServletOutputStream;
  15. import javax.servlet.http.HttpServletResponse;
  16. import java.io.IOException;
  17. import java.io.InputStream;
  18. import java.nio.charset.StandardCharsets;
  19. import java.security.InvalidKeyException;
  20. import java.security.NoSuchAlgorithmException;
  21. import java.util.ArrayList;
  22. import java.util.List;
  23. /**
  24. * MinIO 客户端工具类
  25. */
  26. @Component
  27. @Slf4j
  28. public class MinioClientUtils {
  29. @Autowired
  30. private MinioClient minioClient;
  31. private static final int DEFAULT_EXPIRY_TIME = 7 * 24 * 3600;
  32. /**
  33. * 检查存储桶是否存在
  34. *
  35. * @param bucketName 存储桶名称
  36. * @return boolean
  37. */
  38. public boolean bucketExists(String bucketName) throws IOException, InvalidKeyException, InvalidResponseException, InsufficientDataException, NoSuchAlgorithmException, ServerException, InternalException, XmlParserException, InvalidBucketNameException, ErrorResponseException {
  39. boolean flag = false;
  40. flag = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
  41. if (flag) {
  42. return true;
  43. }
  44. return false;
  45. }
  46. /**
  47. * 创建存储桶
  48. *
  49. * @param bucketName 存储桶名称
  50. */
  51. public boolean makeBucket(String bucketName) throws IOException, InvalidKeyException, InvalidResponseException, RegionConflictException, InsufficientDataException, NoSuchAlgorithmException, ServerException, InternalException, XmlParserException, InvalidBucketNameException, ErrorResponseException {
  52. boolean flag = bucketExists(bucketName);
  53. if (!flag) {
  54. minioClient.makeBucket(
  55. MakeBucketArgs.builder()
  56. .bucket(bucketName)
  57. .build());
  58. return true;
  59. } else {
  60. return false;
  61. }
  62. }
  63. /**
  64. * 列出所有存储桶名称
  65. *
  66. * @return List<String>
  67. */
  68. public List<String> listBucketNames() throws IOException, InvalidResponseException, InvalidKeyException, NoSuchAlgorithmException, ServerException, ErrorResponseException, XmlParserException, InvalidBucketNameException, InsufficientDataException, InternalException {
  69. List<Bucket> bucketList = listBuckets();
  70. List<String> bucketListName = new ArrayList<>();
  71. for (Bucket bucket : bucketList) {
  72. bucketListName.add(bucket.name());
  73. }
  74. return bucketListName;
  75. }
  76. /**
  77. * 列出所有存储桶
  78. *
  79. * @return List<Bucket>
  80. */
  81. public List<Bucket> listBuckets() throws IOException, InvalidKeyException, InvalidResponseException, InsufficientDataException, NoSuchAlgorithmException, ServerException, InternalException, XmlParserException, InvalidBucketNameException, ErrorResponseException {
  82. return minioClient.listBuckets();
  83. }
  84. /**
  85. * 删除存储桶
  86. *
  87. * @param bucketName 存储桶名称
  88. * @return boolean
  89. */
  90. public boolean removeBucket(String bucketName) throws IOException, InvalidKeyException, InvalidResponseException, InsufficientDataException, NoSuchAlgorithmException, ServerException, InternalException, XmlParserException, InvalidBucketNameException, ErrorResponseException {
  91. boolean flag = bucketExists(bucketName);
  92. if (flag) {
  93. Iterable<Result<Item>> myObjects = listObjects(bucketName);
  94. for (Result<Item> result : myObjects) {
  95. Item item = result.get();
  96. // 有对象文件,则删除失败
  97. if (item.size() > 0) {
  98. return false;
  99. }
  100. }
  101. // 删除存储桶,注意,只有存储桶为空时才能删除成功。
  102. minioClient.removeBucket(RemoveBucketArgs.builder().bucket(bucketName).build());
  103. flag = bucketExists(bucketName);
  104. if (!flag) {
  105. return true;
  106. }
  107. }
  108. return false;
  109. }
  110. /**
  111. * 列出存储桶中的所有对象名称
  112. *
  113. * @param bucketName 存储桶名称
  114. * @return List<String>
  115. */
  116. public List<String> listObjectNames(String bucketName) throws XmlParserException, IOException, InvalidResponseException, InvalidKeyException, NoSuchAlgorithmException, ServerException, ErrorResponseException, InvalidBucketNameException, InsufficientDataException, InternalException {
  117. List<String> listObjectNames = new ArrayList<>();
  118. boolean flag = bucketExists(bucketName);
  119. if (flag) {
  120. Iterable<Result<Item>> myObjects = listObjects(bucketName);
  121. for (Result<Item> result : myObjects) {
  122. Item item = result.get();
  123. listObjectNames.add(item.objectName());
  124. }
  125. }
  126. return listObjectNames;
  127. }
  128. /**
  129. * 列出存储桶中的所有对象
  130. *
  131. * @param bucketName 存储桶名称
  132. * @return Iterable<Result<Item>>
  133. */
  134. public Iterable<Result<Item>> listObjects(String bucketName) throws XmlParserException, IOException, InvalidResponseException, InvalidKeyException, NoSuchAlgorithmException, ServerException, ErrorResponseException, InvalidBucketNameException, InsufficientDataException, InternalException {
  135. boolean flag = bucketExists(bucketName);
  136. if (flag) {
  137. return minioClient.listObjects( ListObjectsArgs.builder().bucket(bucketName).build());
  138. }
  139. return null;
  140. }
  141. /**
  142. * 通过文件上传到对象
  143. *
  144. * @param bucketName 存储桶名称
  145. * @param objectName 存储桶里的对象名称
  146. * @param fileName File name
  147. * @return boolean
  148. */
  149. public boolean uploadObject(String bucketName, String objectName, String fileName) throws IOException, InvalidKeyException, InvalidResponseException, InsufficientDataException, NoSuchAlgorithmException, ServerException, InternalException, XmlParserException, InvalidBucketNameException, ErrorResponseException {
  150. boolean flag = bucketExists(bucketName);
  151. if (flag) {
  152. minioClient.uploadObject(
  153. UploadObjectArgs.builder()
  154. .bucket(bucketName).object(objectName).filename(fileName).build());
  155. ObjectStat statObject = statObject(bucketName, objectName);
  156. if (statObject != null && statObject.length() > 0) {
  157. return true;
  158. }
  159. }
  160. return false;
  161. }
  162. /**
  163. * 文件上传
  164. *
  165. * @param bucketName 存储捅名称
  166. * @param multipartFile 文件
  167. * @param filename 文件名
  168. */
  169. public void putObject(String bucketName, MultipartFile multipartFile, String filename) throws IOException, InvalidKeyException, InvalidResponseException, InsufficientDataException, NoSuchAlgorithmException, ServerException, InternalException, XmlParserException, InvalidBucketNameException, ErrorResponseException {
  170. PutObjectOptions putObjectOptions = new PutObjectOptions(multipartFile.getSize(), PutObjectOptions.MIN_MULTIPART_SIZE);
  171. putObjectOptions.setContentType(multipartFile.getContentType());
  172. minioClient.putObject(
  173. PutObjectArgs.builder().bucket(bucketName).object(filename).stream(
  174. multipartFile.getInputStream(), multipartFile.getSize(), -1).contentType(multipartFile.getContentType())
  175. .build());
  176. }
  177. /**
  178. * 通过InputStream上传对象
  179. *
  180. * @param bucketName 存储桶名称
  181. * @param objectName 存储桶里的对象名称
  182. * @param inputStream 要上传的流
  183. * @param contentType 上传的文件类型 例如 video/mp4 image/jpg
  184. * @return boolean
  185. */
  186. public boolean putObject(String bucketName, String objectName, InputStream inputStream,String contentType) throws IOException, InvalidResponseException, InvalidKeyException, NoSuchAlgorithmException, ServerException, ErrorResponseException, XmlParserException, InvalidBucketNameException, InsufficientDataException, InternalException {
  187. boolean flag = bucketExists(bucketName);
  188. if (flag) {
  189. minioClient.putObject(PutObjectArgs.builder().bucket(bucketName).object(objectName).stream(
  190. //不清楚文件的大小时,可以传-1,10485760。如果知道大小也可以传入size,partsize。
  191. inputStream, -1, 10485760)
  192. .contentType(contentType)
  193. .build());
  194. ObjectStat statObject = statObject(bucketName, objectName);
  195. if (statObject != null && statObject.length() > 0) {
  196. return true;
  197. }
  198. }
  199. return false;
  200. }
  201. /**
  202. * 以流的形式获取一个文件对象
  203. *
  204. * @param bucketName 存储桶名称
  205. * @param objectName 存储桶里的对象名称
  206. * @return InputStream
  207. */
  208. public InputStream getObject(String bucketName, String objectName) throws IOException, InvalidKeyException, InvalidResponseException, InsufficientDataException, NoSuchAlgorithmException, ServerException, InternalException, XmlParserException, InvalidBucketNameException, ErrorResponseException {
  209. boolean flag = bucketExists(bucketName);
  210. if (flag) {
  211. ObjectStat statObject = statObject(bucketName, objectName);
  212. if (statObject != null && statObject.length() > 0) {
  213. InputStream stream = minioClient.getObject( GetObjectArgs.builder()
  214. .bucket(bucketName)
  215. .object(objectName)
  216. .build());
  217. return stream;
  218. }
  219. }
  220. return null;
  221. }
  222. /**
  223. * 以流的形式获取一个文件对象(断点下载)
  224. *
  225. * @param bucketName 存储桶名称
  226. * @param objectName 存储桶里的对象名称
  227. * @param offset 起始字节的位置
  228. * @param length 要读取的长度 (可选,如果无值则代表读到文件结尾)
  229. * @return InputStream
  230. */
  231. public InputStream getObject(String bucketName, String objectName, long offset, Long length) throws IOException, InvalidKeyException, InvalidResponseException, InsufficientDataException, NoSuchAlgorithmException, ServerException, InternalException, XmlParserException, InvalidBucketNameException, ErrorResponseException {
  232. boolean flag = bucketExists(bucketName);
  233. if (flag) {
  234. ObjectStat statObject = statObject(bucketName, objectName);
  235. if (statObject != null && statObject.length() > 0) {
  236. InputStream stream = minioClient.getObject( GetObjectArgs.builder()
  237. .bucket(bucketName)
  238. .object(objectName)
  239. .offset(1024L)
  240. .length(4096L)
  241. .build());
  242. return stream;
  243. }
  244. }
  245. return null;
  246. }
  247. /**
  248. * 下载并将文件保存到本地
  249. *
  250. * @param bucketName 存储桶名称
  251. * @param objectName 存储桶里的对象名称
  252. * @param fileName File name
  253. * @return boolean
  254. */
  255. public boolean downloadObject(String bucketName, String objectName, String fileName) throws IOException, InvalidKeyException, InvalidResponseException, InsufficientDataException, NoSuchAlgorithmException, ServerException, InternalException, XmlParserException, InvalidBucketNameException, ErrorResponseException {
  256. boolean flag = bucketExists(bucketName);
  257. if (flag) {
  258. ObjectStat statObject = statObject(bucketName, objectName);
  259. if (statObject != null && statObject.length() > 0) {
  260. minioClient.downloadObject(DownloadObjectArgs.builder()
  261. .bucket(bucketName)
  262. .object(objectName)
  263. .filename(fileName)
  264. .build());
  265. return true;
  266. }
  267. }
  268. return false;
  269. }
  270. /**
  271. * 删除一个对象
  272. *
  273. * @param bucketName 存储桶名称
  274. * @param objectName 存储桶里的对象名称
  275. */
  276. public boolean removeObject(String bucketName, String objectName) throws IOException, InvalidKeyException, InvalidResponseException, InsufficientDataException, NoSuchAlgorithmException, ServerException, InternalException, XmlParserException, InvalidBucketNameException, ErrorResponseException {
  277. boolean flag = bucketExists(bucketName);
  278. if (flag) {
  279. minioClient.removeObject(RemoveObjectArgs.builder().bucket(bucketName).object(objectName).build());
  280. return true;
  281. }
  282. return false;
  283. }
  284. /**
  285. * 删除指定桶的多个文件对象,返回删除错误的对象列表,全部删除成功,返回空列表
  286. *
  287. * @param bucketName 存储桶名称
  288. * @param objectNames 含有要删除的多个object名称的迭代器对象
  289. * @return
  290. * eg:
  291. * List<DeleteObject> objects = new LinkedList<>();
  292. * objects.add(new DeleteObject("my-objectname1"));
  293. * objects.add(new DeleteObject("my-objectname2"));
  294. * objects.add(new DeleteObject("my-objectname3"));
  295. */
  296. public List<String> removeObjects(String bucketName, List<DeleteObject> objectNames) throws IOException, InvalidKeyException, InvalidResponseException, InsufficientDataException, NoSuchAlgorithmException, ServerException, InternalException, XmlParserException, InvalidBucketNameException, ErrorResponseException {
  297. List<String> deleteErrorNames = new ArrayList<>();
  298. boolean flag = bucketExists(bucketName);
  299. if (flag) {
  300. Iterable<Result<DeleteError>> results = minioClient.removeObjects(RemoveObjectsArgs.builder().bucket(bucketName).objects(objectNames).build());
  301. for (Result<DeleteError> result : results) {
  302. DeleteError error = result.get();
  303. deleteErrorNames.add(error.objectName());
  304. }
  305. }
  306. return deleteErrorNames;
  307. }
  308. /**
  309. * 生成一个给HTTP GET请求用的presigned URL。
  310. * 浏览器/移动端的客户端可以用这个URL进行下载,即使其所在的存储桶是私有的。这个presigned URL可以设置一个失效时间,默认值是7天。
  311. *
  312. * @param bucketName 存储桶名称
  313. * @param objectName 存储桶里的对象名称
  314. * @param expires 失效时间(以秒为单位),默认是7天,不得大于七天
  315. * @return
  316. */
  317. public String getPresignedObjectUrl(String bucketName, String objectName, Integer expires) throws InvalidExpiresRangeException, IOException, InvalidResponseException, InvalidKeyException, NoSuchAlgorithmException, ServerException, ErrorResponseException, XmlParserException, InvalidBucketNameException, InsufficientDataException, InternalException {
  318. boolean flag = bucketExists(bucketName);
  319. String url = "";
  320. if (flag) {
  321. if (expires < 1 || expires > DEFAULT_EXPIRY_TIME) {
  322. throw new InvalidExpiresRangeException(expires,
  323. "expires must be in range of 1 to " + DEFAULT_EXPIRY_TIME);
  324. }
  325. try {
  326. url = minioClient.getPresignedObjectUrl(GetPresignedObjectUrlArgs.builder()
  327. .method(Method.GET)
  328. .bucket(bucketName)
  329. .object(objectName)
  330. .expiry(expires)//动态参数
  331. // .expiry(24 * 60 * 60)//用秒来计算一天时间有效期
  332. // .expiry(1, TimeUnit.DAYS)//按天传参
  333. // .expiry(1, TimeUnit.HOURS)//按小时传参数
  334. .build());
  335. } catch (ErrorResponseException | InsufficientDataException | InternalException | InvalidBucketNameException | InvalidExpiresRangeException | InvalidKeyException | InvalidResponseException | IOException | NoSuchAlgorithmException | ServerException | XmlParserException e) {
  336. e.printStackTrace();
  337. }
  338. }
  339. return url;
  340. }
  341. /**
  342. * 生成一个给HTTP PUT请求用的presigned URL。
  343. * 浏览器/移动端的客户端可以用这个URL进行上传,即使其所在的存储桶是私有的。这个presigned URL可以设置一个失效时间,默认值是7天。
  344. *
  345. * @param bucketName 存储桶名称
  346. * @param objectName 存储桶里的对象名称
  347. * @param expires 失效时间(以秒为单位),默认是7天,不得大于七天
  348. * @return String
  349. */
  350. public String presignedPutObject(String bucketName, String objectName, Integer expires) throws IOException, InvalidResponseException, InvalidKeyException, NoSuchAlgorithmException, ServerException, ErrorResponseException, XmlParserException, InvalidBucketNameException, InsufficientDataException, InternalException {
  351. boolean flag = bucketExists(bucketName);
  352. String url = "";
  353. if (flag) {
  354. if (expires < 1 || expires > DEFAULT_EXPIRY_TIME) {
  355. try {
  356. throw new InvalidExpiresRangeException(expires,
  357. "expires must be in range of 1 to " + DEFAULT_EXPIRY_TIME);
  358. } catch (InvalidExpiresRangeException e) {
  359. e.printStackTrace();
  360. }
  361. }
  362. try {
  363. url = minioClient.getPresignedObjectUrl(GetPresignedObjectUrlArgs.builder()
  364. .method(Method.PUT)
  365. .bucket(bucketName)
  366. .object(objectName)
  367. .expiry(expires)//动态参数
  368. // .expiry(24 * 60 * 60)//用秒来计算一天时间有效期
  369. // .expiry(1, TimeUnit.DAYS)//按天传参
  370. // .expiry(1, TimeUnit.HOURS)//按小时传参数
  371. .build());
  372. } catch (ErrorResponseException | InsufficientDataException e) {
  373. e.printStackTrace();
  374. } catch (InternalException e) {
  375. log.error("InternalException",e);
  376. } catch (InvalidBucketNameException e) {
  377. log.error("InvalidBucketNameException",e);
  378. } catch (InvalidExpiresRangeException e) {
  379. log.error("InvalidExpiresRangeException",e);
  380. } catch (InvalidKeyException e) {
  381. log.error("InvalidKeyException",e);
  382. } catch (InvalidResponseException e) {
  383. log.error("InvalidResponseException",e);
  384. } catch (IOException e) {
  385. log.error("IOException",e);
  386. } catch (NoSuchAlgorithmException e) {
  387. log.error("NoSuchAlgorithmException",e);
  388. } catch (ServerException e) {
  389. log.error("ServerException",e);
  390. } catch (XmlParserException e) {
  391. log.error("XmlParserException",e);
  392. }
  393. }
  394. return url;
  395. }
  396. /**
  397. * 获取对象的元数据
  398. *
  399. * @param bucketName 存储桶名称
  400. * @param objectName 存储桶里的对象名称
  401. * @return
  402. */
  403. public ObjectStat statObject(String bucketName, String objectName) throws IOException, InvalidResponseException, InvalidKeyException, NoSuchAlgorithmException, ServerException, ErrorResponseException, XmlParserException, InvalidBucketNameException, InsufficientDataException, InternalException {
  404. boolean flag = bucketExists(bucketName);
  405. if (flag) {
  406. ObjectStat statObject = null;
  407. try {
  408. statObject = minioClient.statObject(StatObjectArgs.builder().bucket(bucketName).object(objectName).build());
  409. } catch (ErrorResponseException e) {
  410. log.error("ErrorResponseException",e);
  411. } catch (InsufficientDataException e) {
  412. log.error("ErrorResponseException",e);
  413. e.printStackTrace();
  414. } catch (InternalException e) {
  415. log.error("InternalException",e);
  416. } catch (InvalidBucketNameException e) {
  417. log.error("InvalidBucketNameException",e);
  418. } catch (InvalidKeyException e) {
  419. log.error("InvalidKeyException",e);
  420. } catch (InvalidResponseException e) {
  421. log.error("InvalidResponseException",e);
  422. } catch (IOException e) {
  423. log.error("IOException",e);
  424. } catch (NoSuchAlgorithmException e) {
  425. log.error("NoSuchAlgorithmException",e);
  426. } catch (ServerException e) {
  427. log.error("ServerException",e);
  428. } catch (XmlParserException e) {
  429. log.error("XmlParserException",e);
  430. }
  431. return statObject;
  432. }
  433. return null;
  434. }
  435. /**
  436. * 文件访问路径
  437. *
  438. * @param bucketName 存储桶名称
  439. * @param objectName 存储桶里的对象名称
  440. * @return String
  441. */
  442. public String getObjectUrl(String bucketName, String objectName) throws IOException, InvalidResponseException, InvalidKeyException, NoSuchAlgorithmException, ServerException, ErrorResponseException, XmlParserException, InvalidBucketNameException, InsufficientDataException, InternalException {
  443. boolean flag = bucketExists(bucketName);
  444. String url = "";
  445. if (flag) {
  446. try {
  447. url = minioClient.getObjectUrl(bucketName, objectName);
  448. } catch (ErrorResponseException e) {
  449. log.error("XmlParserException",e);
  450. } catch (InsufficientDataException e) {
  451. log.error("InsufficientDataException",e);
  452. } catch (InternalException e) {
  453. log.error("InternalException",e);
  454. } catch (InvalidBucketNameException e) {
  455. log.error("InvalidBucketNameException",e);
  456. } catch (InvalidKeyException e) {
  457. log.error("InvalidKeyException",e);
  458. } catch (InvalidResponseException e) {
  459. log.error("InvalidResponseException",e);
  460. } catch (IOException e) {
  461. log.error("IOException",e);
  462. } catch (NoSuchAlgorithmException e) {
  463. log.error("NoSuchAlgorithmException",e);
  464. } catch (ServerException e) {
  465. log.error("ServerException",e);
  466. } catch (XmlParserException e) {
  467. log.error("XmlParserException",e);
  468. }
  469. }
  470. return url;
  471. }
  472. public void downloadFile(String bucketName, String fileName, String originalName, HttpServletResponse response) {
  473. try {
  474. InputStream file = minioClient.getObject(GetObjectArgs.builder()
  475. .bucket(bucketName)
  476. .object(fileName)
  477. .build());
  478. String filename = new String(fileName.getBytes("ISO8859-1"), StandardCharsets.UTF_8);
  479. if (StringUtils.isNotEmpty(originalName)) {
  480. fileName = originalName;
  481. }
  482. response.setHeader("Content-Disposition", "attachment;filename=" + filename);
  483. ServletOutputStream servletOutputStream = response.getOutputStream();
  484. int len;
  485. byte[] buffer = new byte[1024];
  486. while ((len = file.read(buffer)) > 0) {
  487. servletOutputStream.write(buffer, 0, len);
  488. }
  489. servletOutputStream.flush();
  490. file.close();
  491. servletOutputStream.close();
  492. } catch (ErrorResponseException e) {
  493. log.error("ErrorResponseException",e);
  494. } catch (Exception e) {
  495. log.error("Exception",e);
  496. }
  497. }
  498. }

2.4 创建一个数据表,用于保存上传到minio的文件的信息

  1. CREATE TABLE `minio_file` (
  2. `id` bigint(20) NOT NULL COMMENT '文件id',
  3. `original_file_name` varchar(255) COLLATE utf8mb4_bin DEFAULT NULL COMMENT '原始文件名称',
  4. `file_ext_name` varchar(15) COLLATE utf8mb4_bin DEFAULT NULL COMMENT '文件拓展名',
  5. `file_size` bigint(20) DEFAULT NULL COMMENT '文件大小(单位:字节)',
  6. `file_name` varchar(35) COLLATE utf8mb4_bin DEFAULT NULL COMMENT '存入minio时的文件名称',
  7. `mime` varchar(50) COLLATE utf8mb4_bin DEFAULT NULL COMMENT '文件的content-type',
  8. `file_url` varchar(255) COLLATE utf8mb4_bin DEFAULT NULL COMMENT '文件路径',
  9. `is_delete` tinyint(1) DEFAULT NULL COMMENT '是否删除 0 否 1 是',
  10. `create_by` varchar(25) COLLATE utf8mb4_bin DEFAULT NULL COMMENT '创建者',
  11. `update_by` varchar(25) COLLATE utf8mb4_bin DEFAULT NULL COMMENT '更改者',
  12. `create_time` datetime DEFAULT NULL COMMENT '创建时间',
  13. `update_time` datetime DEFAULT NULL COMMENT '更新时间',
  14. PRIMARY KEY (`id`)
  15. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;

2.5 使用代码自动生成器生成entity、controller、service、mapper。

代码自动生成器文章地址:代码自动生成器_芒果味的戏子的博客-CSDN博客

2.6 创建minio上传、删除接口

  1. import cn.hutool.core.io.FileUtil;
  2. import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
  3. import io.swagger.annotations.Api;
  4. import io.swagger.annotations.ApiImplicitParam;
  5. import io.swagger.annotations.ApiOperation;
  6. import lombok.extern.slf4j.Slf4j;
  7. import org.apache.commons.collections4.CollectionUtils;
  8. import org.apache.commons.lang3.RandomStringUtils;
  9. import org.apache.commons.lang3.math.NumberUtils;
  10. import org.jeecg.common.api.vo.Result;
  11. import org.jeecg.config.oss.MinioConfig;
  12. import org.jeecg.modules.dto.MinioResponseDTO;
  13. import org.jeecg.modules.entity.MinioFile;
  14. import org.jeecg.modules.service.MinioFileService;
  15. import org.jeecg.modules.util.MinioClientUtils;
  16. import org.springframework.beans.factory.annotation.Autowired;
  17. import org.springframework.web.bind.annotation.*;
  18. import org.springframework.web.multipart.MultipartFile;
  19. import javax.annotation.Resource;
  20. import java.time.Instant;
  21. import java.util.ArrayList;
  22. import java.util.List;
  23. /**
  24. * @author xiaomifeng1010
  25. * @version 1.0
  26. * @date: 2022/5/21 10:33
  27. * @Description minio 文件处理(上传,下载,获取文件地址等)
  28. */
  29. @Slf4j
  30. @Api(tags = "文件处理模块")
  31. @RestController
  32. @CrossOrigin //处理跨域请求
  33. @RequestMapping("/minioFile")
  34. public class MinioFileController {
  35. @Resource
  36. private MinioClientUtils minioClientUtils;
  37. @Resource
  38. private MinioConfig minioConfig;
  39. @Autowired
  40. private MinioFileService minioFileService;
  41. @PostMapping(value = "/uploadFile")
  42. @ApiOperation(value = "上传文件,支持批量上传")
  43. @ApiImplicitParam(name = "files",value = "文件对象",dataType = "File")
  44. public Result uploadFile(@RequestParam("files") List<MultipartFile> files) {
  45. log.info(files.toString());
  46. if (CollectionUtils.isEmpty(files)){
  47. return Result.error("未选择文件!");
  48. }
  49. List<MinioResponseDTO> MinioResponseDTOList=new ArrayList<>();
  50. for (MultipartFile file : files) {
  51. String originalFilename = file.getOriginalFilename();
  52. // 获取文件拓展名
  53. String extName = FileUtil.extName(originalFilename);
  54. log.info("文件拓展名:"+extName);
  55. // 生成新的文件名,存入到minio
  56. long millSeconds = Instant.now().toEpochMilli();
  57. String minioFileName=millSeconds+ RandomStringUtils.randomNumeric(12)+"."+extName;
  58. String contentType = file.getContentType();
  59. log.info("文件mime:{}",contentType);
  60. // 返回文件大小,单位字节
  61. long size = file.getSize();
  62. log.info("文件大小:"+size);
  63. try {
  64. String bucketName = minioConfig.getBucketName();
  65. minioClientUtils.putObject(bucketName,file,minioFileName);
  66. String fileUrl = minioClientUtils.getObjectUrl(bucketName, minioFileName);
  67. MinioFile minioFile = new MinioFile();
  68. minioFile.setOriginalFileName(originalFilename);
  69. minioFile.setFileExtName(extName);
  70. minioFile.setFileName(minioFileName);
  71. minioFile.setFileSize(size);
  72. minioFile.setMime(contentType);
  73. // minioFile.setIsDelete(NumberUtils.INTEGER_ZERO);
  74. minioFile.setIsDelete(NumberUtils.INTEGER_ZERO == 0 ? false : true);
  75. minioFile.setFileUrl(fileUrl);
  76. boolean insert = minioFileService.save(minioFile);
  77. if (insert) {
  78. MinioResponseDTO minioResponseDTO = new MinioResponseDTO();
  79. minioResponseDTO.setFileId(minioFile.getId());
  80. minioResponseDTO.setOriginalFileName(originalFilename);
  81. minioResponseDTO.setFileUrl(fileUrl);
  82. MinioResponseDTOList.add(minioResponseDTO);
  83. }
  84. } catch (Exception e) {
  85. log.error("上传文件出错:{}",e);
  86. return Result.error("上传文件出错");
  87. }
  88. }
  89. return Result.ok(MinioResponseDTOList);
  90. }
  91. /**
  92. * 删除文件
  93. * @param minioFileName 文件名称
  94. * @return
  95. */
  96. @ApiOperation(value = "删除文件" , notes = "删除文件")
  97. @RequestMapping(value = "/deleteMinioFile",method = RequestMethod.GET)
  98. public Result<?> deleteMinioFile(@RequestParam String minioFileName){
  99. try {
  100. String bucketName = minioConfig.getBucketName();
  101. minioClientUtils.removeObject(bucketName,minioFileName);
  102. MinioFile minioFile = minioFileService.getOne(new QueryWrapper<MinioFile>().eq("file_name",minioFileName));
  103. if (minioFile == null){
  104. log.error("文件不存在数据库表中!");
  105. return Result.error("文件不存在数据库表中!");
  106. }else{
  107. minioFileService.removeById(minioFile);
  108. }
  109. }catch (Exception e){
  110. log.error("删除文件失败!");
  111. return Result.error("删除文件失败!");
  112. }
  113. return Result.ok("删除文件成功");
  114. }
  115. }

2.7 封装上传返回数据MinioResponseDTO对象

  1. import io.swagger.annotations.ApiModelProperty;
  2. import lombok.Data;
  3. /**
  4. * 该实体主要用于封装用户提交的文件信息表单
  5. *
  6. * @author Lannibar
  7. * @since 2023-5-18
  8. */
  9. @Data
  10. public class MinioResponseDTO {
  11. @ApiModelProperty(value = "文件id")
  12. private Long fileId;
  13. @ApiModelProperty(value = "文件访问地址")
  14. private String fileUrl;
  15. @ApiModelProperty(value = "文件名")
  16. private String originalFileName;
  17. }

2.8 测试

上传:

数据库数据:

 使用返回的访问地址访问: 

删除:

至此,MinIO文件服务的安装和使用已完成。

文章仅供自身学习和参考。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Gausst松鼠会/article/detail/554312
推荐阅读
相关标签
  

闽ICP备14008679号