当前位置:   article > 正文

MinIO实现文件上传下载,前端使用Vue,后端使用SpringBoot_minio文件上传存储后端

minio文件上传存储后端

依赖

  1. <!-- MinIO -->
  2. <dependency>
  3. <groupId>io.minio</groupId>
  4. <artifactId>minio</artifactId>
  5. <version>8.2.2</version>
  6. </dependency>

配置文件

  1. minio:
  2. endpoint: http://118.31.31.1
  3. port: 19000
  4. accessKey: admin1
  5. secretKey: 123456783
  6. bucketName: sif31an1

Minio配置类

  1. import io.minio.MinioClient;
  2. import lombok.Data;
  3. import org.springframework.boot.context.properties.ConfigurationProperties;
  4. import org.springframework.context.annotation.Bean;
  5. import org.springframework.context.annotation.Configuration;
  6. @Configuration
  7. @ConfigurationProperties(prefix = "minio")
  8. @Data
  9. public class MinioConfig {
  10. private String endpoint;
  11. private Integer port;
  12. private String bucketName;
  13. private String accessKey;
  14. private String secretKey;
  15. @Bean
  16. public MinioClient minioClient() {
  17. return MinioClient.builder().endpoint(endpoint, port, false).credentials(accessKey, secretKey).build();
  18. }
  19. }

Minio工具类

  1. import io.minio.*;
  2. import io.minio.http.Method;
  3. import io.minio.messages.Bucket;
  4. import io.minio.messages.DeleteObject;
  5. import io.minio.messages.Item;
  6. import lombok.extern.slf4j.Slf4j;
  7. import org.springframework.beans.factory.annotation.Value;
  8. import org.springframework.stereotype.Component;
  9. import org.springframework.web.multipart.MultipartFile;
  10. import javax.annotation.Resource;
  11. import java.io.ByteArrayInputStream;
  12. import java.io.InputStream;
  13. import java.io.UnsupportedEncodingException;
  14. import java.net.URLDecoder;
  15. import java.util.ArrayList;
  16. import java.util.LinkedList;
  17. import java.util.List;
  18. import java.util.Optional;
  19. /**
  20. * MinIO工具类
  21. *
  22. * @author guoj
  23. * @date 2021/12/14 19:30
  24. */
  25. @Slf4j
  26. @Component
  27. public class MinIOUtils {
  28. @Resource
  29. private MinioClient minioClient;
  30. @Value("${minio.endpoint}")
  31. private String endpoint;
  32. @Value("${minio.bucketName}")
  33. private String bucketName;
  34. @Value("${minio.accessKey}")
  35. private String accessKey;
  36. @Value("${minio.secretKey}")
  37. private String secretKey;
  38. private Integer imgSize = 100 * 1024 * 1024; //100M
  39. private Integer fileSize = 1 * 1024 * 1024 * 1024; //1G
  40. /**
  41. * 获取上传文件前缀路径
  42. *
  43. * @return
  44. */
  45. public String getBasisUrl() {
  46. return endpoint + "-" + bucketName + "-";
  47. }
  48. /****************************** Operate Bucket Start ******************************/
  49. /**
  50. * 启动SpringBoot容器的时候初始化Bucket
  51. * 如果没有Bucket则创建
  52. *
  53. * @throws Exception
  54. */
  55. public void createBucket(String bucketName) throws Exception {
  56. if (!bucketExists(bucketName)) {
  57. minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
  58. }
  59. }
  60. /**
  61. * 判断Bucket是否存在,true:存在,false:不存在
  62. *
  63. * @return
  64. * @throws Exception
  65. */
  66. public boolean bucketExists(String bucketName) throws Exception {
  67. return minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
  68. }
  69. /**
  70. * 获得Bucket的策略
  71. *
  72. * @param bucketName
  73. * @return
  74. * @throws Exception
  75. */
  76. public String getBucketPolicy(String bucketName) throws Exception {
  77. return minioClient
  78. .getBucketPolicy(
  79. GetBucketPolicyArgs
  80. .builder()
  81. .bucket(bucketName)
  82. .build()
  83. );
  84. }
  85. /**
  86. * 获得所有Bucket列表
  87. *
  88. * @return
  89. * @throws Exception
  90. */
  91. public List<Bucket> getAllBuckets() throws Exception {
  92. return minioClient.listBuckets();
  93. }
  94. /**
  95. * 根据bucketName获取其相关信息
  96. *
  97. * @param bucketName
  98. * @return
  99. * @throws Exception
  100. */
  101. public Optional<Bucket> getBucket(String bucketName) throws Exception {
  102. return getAllBuckets().stream().filter(b -> b.name().equals(bucketName)).findFirst();
  103. }
  104. /**
  105. * 根据bucketName删除Bucket,true:删除成功; false:删除失败,文件或已不存在
  106. *
  107. * @param bucketName
  108. * @throws Exception
  109. */
  110. public void removeBucket(String bucketName) throws Exception {
  111. minioClient.removeBucket(RemoveBucketArgs.builder().bucket(bucketName).build());
  112. }
  113. /****************************** Operate Bucket End ******************************/
  114. /****************************** Operate Files Start ******************************/
  115. /**
  116. * 判断文件是否存在
  117. *
  118. * @param bucketName 存储桶
  119. * @param objectName 文件名
  120. * @return
  121. */
  122. public boolean isObjectExist(String bucketName, String objectName) {
  123. boolean exist = true;
  124. try {
  125. minioClient.statObject(StatObjectArgs.builder().bucket(bucketName).object(objectName).build());
  126. } catch (Exception e) {
  127. log.error("[Minio工具类]>>>> 判断文件是否存在, 异常:", e);
  128. exist = false;
  129. }
  130. return exist;
  131. }
  132. /**
  133. * 判断文件夹是否存在
  134. *
  135. * @param bucketName 存储桶
  136. * @param objectName 文件夹名称
  137. * @return
  138. */
  139. public boolean isFolderExist(String bucketName, String objectName) {
  140. boolean exist = false;
  141. try {
  142. Iterable<Result<Item>> results = minioClient.listObjects(
  143. ListObjectsArgs.builder().bucket(bucketName).prefix(objectName).recursive(false).build());
  144. for (Result<Item> result : results) {
  145. Item item = result.get();
  146. if (item.isDir() && objectName.equals(item.objectName())) {
  147. exist = true;
  148. }
  149. }
  150. } catch (Exception e) {
  151. log.error("[Minio工具类]>>>> 判断文件夹是否存在,异常:", e);
  152. exist = false;
  153. }
  154. return exist;
  155. }
  156. /**
  157. * 根据文件前置查询文件
  158. *
  159. * @param bucketName 存储桶
  160. * @param prefix 前缀
  161. * @param recursive 是否使用递归查询
  162. * @return MinioItem 列表
  163. * @throws Exception
  164. */
  165. public List<Item> getAllObjectsByPrefix(String bucketName,
  166. String prefix,
  167. boolean recursive) throws Exception {
  168. List<Item> list = new ArrayList<>();
  169. Iterable<Result<Item>> objectsIterator = minioClient.listObjects(
  170. ListObjectsArgs.builder().bucket(bucketName).prefix(prefix).recursive(recursive).build());
  171. if (objectsIterator != null) {
  172. for (Result<Item> o : objectsIterator) {
  173. Item item = o.get();
  174. list.add(item);
  175. }
  176. }
  177. return list;
  178. }
  179. /**
  180. * 获取文件流
  181. *
  182. * @param bucketName 存储桶
  183. * @param objectName 文件名
  184. * @return 二进制流
  185. */
  186. public InputStream getObject(String bucketName, String objectName) throws Exception {
  187. return minioClient.getObject(GetObjectArgs.builder().bucket(bucketName).object(objectName).build());
  188. }
  189. /**
  190. * 断点下载
  191. *
  192. * @param bucketName 存储桶
  193. * @param objectName 文件名称
  194. * @param offset 起始字节的位置
  195. * @param length 要读取的长度
  196. * @return 二进制流
  197. */
  198. public InputStream getObject(String bucketName, String objectName, long offset, long length) throws Exception {
  199. return minioClient.getObject(
  200. GetObjectArgs.builder()
  201. .bucket(bucketName)
  202. .object(objectName)
  203. .offset(offset)
  204. .length(length)
  205. .build());
  206. }
  207. /**
  208. * 获取路径下文件列表
  209. *
  210. * @param bucketName 存储桶
  211. * @param prefix 文件名称
  212. * @param recursive 是否递归查找,false:模拟文件夹结构查找
  213. * @return 二进制流
  214. */
  215. public Iterable<Result<Item>> listObjects(String bucketName, String prefix,
  216. boolean recursive) {
  217. return minioClient.listObjects(
  218. ListObjectsArgs.builder()
  219. .bucket(bucketName)
  220. .prefix(prefix)
  221. .recursive(recursive)
  222. .build());
  223. }
  224. /**
  225. * 使用MultipartFile进行文件上传
  226. *
  227. * @param bucketName 存储桶
  228. * @param file 文件名
  229. * @param objectName 对象名
  230. * @param contentType 类型
  231. * @return
  232. * @throws Exception
  233. */
  234. public ObjectWriteResponse uploadFile(String bucketName, MultipartFile file,
  235. String objectName, String contentType) throws Exception {
  236. InputStream inputStream = file.getInputStream();
  237. return minioClient.putObject(
  238. PutObjectArgs.builder()
  239. .bucket(bucketName)
  240. .object(objectName)
  241. .contentType(contentType)
  242. .stream(inputStream, inputStream.available(), -1)
  243. .build());
  244. }
  245. /**
  246. * 上传本地文件
  247. *
  248. * @param bucketName 存储桶
  249. * @param objectName 对象名称
  250. * @param fileName 本地文件路径
  251. */
  252. public ObjectWriteResponse uploadFile(String bucketName, String objectName,
  253. String fileName) throws Exception {
  254. return minioClient.uploadObject(
  255. UploadObjectArgs.builder()
  256. .bucket(bucketName)
  257. .object(objectName)
  258. .filename(fileName)
  259. .build());
  260. }
  261. /**
  262. * 通过流上传文件
  263. *
  264. * @param bucketName 存储桶
  265. * @param objectName 文件对象
  266. * @param inputStream 文件流
  267. */
  268. public ObjectWriteResponse uploadFile(String bucketName, String objectName, InputStream inputStream) throws Exception {
  269. return minioClient.putObject(
  270. PutObjectArgs.builder()
  271. .bucket(bucketName)
  272. .object(objectName)
  273. .stream(inputStream, inputStream.available(), -1)
  274. .build());
  275. }
  276. /**
  277. * 创建文件夹或目录
  278. *
  279. * @param bucketName 存储桶
  280. * @param objectName 目录路径
  281. */
  282. public ObjectWriteResponse createDir(String bucketName, String objectName) throws Exception {
  283. return minioClient.putObject(
  284. PutObjectArgs.builder()
  285. .bucket(bucketName)
  286. .object(objectName)
  287. .stream(new ByteArrayInputStream(new byte[]{}), 0, -1)
  288. .build());
  289. }
  290. /**
  291. * 获取文件信息, 如果抛出异常则说明文件不存在
  292. *
  293. * @param bucketName 存储桶
  294. * @param objectName 文件名称
  295. */
  296. public String getFileStatusInfo(String bucketName, String objectName) throws Exception {
  297. return minioClient.statObject(
  298. StatObjectArgs.builder()
  299. .bucket(bucketName)
  300. .object(objectName)
  301. .build()).toString();
  302. }
  303. /**
  304. * 拷贝文件
  305. *
  306. * @param bucketName 存储桶
  307. * @param objectName 文件名
  308. * @param srcBucketName 目标存储桶
  309. * @param srcObjectName 目标文件名
  310. */
  311. public ObjectWriteResponse copyFile(String bucketName, String objectName,
  312. String srcBucketName, String srcObjectName) throws Exception {
  313. return minioClient.copyObject(
  314. CopyObjectArgs.builder()
  315. .source(CopySource.builder().bucket(bucketName).object(objectName).build())
  316. .bucket(srcBucketName)
  317. .object(srcObjectName)
  318. .build());
  319. }
  320. /**
  321. * 删除文件
  322. *
  323. * @param bucketName 存储桶
  324. * @param objectName 文件名称
  325. */
  326. public void removeFile(String bucketName, String objectName) throws Exception {
  327. minioClient.removeObject(
  328. RemoveObjectArgs.builder()
  329. .bucket(bucketName)
  330. .object(objectName)
  331. .build());
  332. }
  333. /**
  334. * 批量删除文件
  335. *
  336. * @param bucketName 存储桶
  337. * @param keys 需要删除的文件列表
  338. * @return
  339. */
  340. public void removeFiles(String bucketName, List<String> keys) {
  341. List<DeleteObject> objects = new LinkedList<>();
  342. keys.forEach(s -> {
  343. objects.add(new DeleteObject(s));
  344. try {
  345. removeFile(bucketName, s);
  346. } catch (Exception e) {
  347. log.error("[Minio工具类]>>>> 批量删除文件,异常:", e);
  348. }
  349. });
  350. }
  351. /**
  352. * 获取文件外链
  353. *
  354. * @param bucketName 存储桶
  355. * @param objectName 文件名
  356. * @param expires 过期时间 <=7 秒 (外链有效时间(单位:秒))
  357. * @return url
  358. * @throws Exception
  359. */
  360. public String getPresignedObjectUrl(String bucketName, String objectName, Integer expires) throws Exception {
  361. GetPresignedObjectUrlArgs args = GetPresignedObjectUrlArgs.builder().expiry(expires).bucket(bucketName).object(objectName).build();
  362. return minioClient.getPresignedObjectUrl(args);
  363. }
  364. /**
  365. * 获得文件外链,失效时间默认是7天
  366. *
  367. * @param bucketName
  368. * @param objectName
  369. * @return url
  370. * @throws Exception
  371. */
  372. public String getPresignedObjectUrl(String bucketName, String objectName) throws Exception {
  373. GetPresignedObjectUrlArgs args = GetPresignedObjectUrlArgs.builder()
  374. .bucket(bucketName)
  375. .object(objectName)
  376. .method(Method.GET).build();
  377. return minioClient.getPresignedObjectUrl(args);
  378. }
  379. /**
  380. * 将URLDecoder编码转成UTF8
  381. *
  382. * @param str
  383. * @return
  384. * @throws UnsupportedEncodingException
  385. */
  386. public String getUtf8ByURLDecoder(String str) throws UnsupportedEncodingException {
  387. String url = str.replaceAll("%(?![0-9a-fA-F]{2})", "%25");
  388. return URLDecoder.decode(url, "UTF-8");
  389. }
  390. /****************************** Operate Files End ******************************/
  391. }

控制器

  1. import com.sifan.erp.config.MinioConfig;
  2. import com.sifan.erp.domain.MinioObject;
  3. import com.sifan.erp.dto.Result;
  4. import com.sifan.erp.service.MinioObjectService;
  5. import com.sifan.erp.utils.MinIOUtils;
  6. import io.minio.MinioClient;
  7. import io.minio.ObjectWriteResponse;
  8. import io.minio.StatObjectArgs;
  9. import io.minio.StatObjectResponse;
  10. import lombok.extern.slf4j.Slf4j;
  11. import org.springframework.web.bind.annotation.PostMapping;
  12. import org.springframework.web.bind.annotation.RequestMapping;
  13. import org.springframework.web.bind.annotation.RequestParam;
  14. import org.springframework.web.bind.annotation.RestController;
  15. import org.springframework.web.multipart.MultipartFile;
  16. import javax.annotation.Resource;
  17. import javax.servlet.http.HttpServletResponse;
  18. import java.text.SimpleDateFormat;
  19. import java.util.Date;
  20. import java.util.UUID;
  21. @Slf4j
  22. @RestController
  23. @RequestMapping("/minio")
  24. public class MinioController {
  25. @Resource
  26. private MinIOUtils minIOUtils;
  27. @Resource
  28. private MinioConfig minioConfig;
  29. @Resource
  30. private MinioClient minioClient;
  31. @Resource
  32. private MinioObjectService minioObjectService;
  33. /**
  34. * @param file
  35. * @return
  36. */
  37. @PostMapping("/uploadCreative")
  38. public Result uploadCreativeScript(@RequestParam("file") MultipartFile file) {
  39. Result result = new Result();
  40. if (file == null) {
  41. result.setMessage("文件为空");
  42. return result;
  43. }
  44. final MinioObject minioObject = new MinioObject();
  45. // 1. 文件名处理
  46. String fileName = file.getOriginalFilename();
  47. String objectName = new SimpleDateFormat("yyyy/MM/dd/").format(new Date())
  48. + fileName.substring(0, fileName.indexOf('.') - 1)
  49. + "-" + UUID.randomUUID().toString().replaceAll("-", "")
  50. + fileName.substring(fileName.lastIndexOf("."));
  51. String contentType = file.getContentType();
  52. // 桶名称长度为3-63个字符,不能有大写字母
  53. String bucketName = "productcreative";
  54. try {
  55. //如果桶不存在,则创建桶
  56. minIOUtils.createBucket(bucketName);
  57. ObjectWriteResponse owr = minIOUtils.uploadFile(bucketName, file, objectName, contentType);
  58. result.setMessage("文件上传成功");
  59. minioObject.setBucketName(bucketName);
  60. minioObject.setContentType(contentType);
  61. minioObject.setCreatedTime(new Date());
  62. minioObject.setEtag(owr.etag());
  63. StatObjectResponse statObjectResponse = minioClient.statObject(StatObjectArgs.builder().bucket(bucketName).object(objectName).build());
  64. minioObject.setLength(statObjectResponse.size());
  65. minioObject.setName(objectName);
  66. //插入MinioObject数据,查询Id
  67. Integer minioObjectId = minioObjectService.insertSelectId(minioObject);
  68. result.setData(minioObjectId);
  69. } catch (Exception e) {
  70. result.setMessage("文件上传失败:" + e.getMessage());
  71. e.printStackTrace();
  72. }
  73. return result;
  74. }
  75. //https://blog.csdn.net/aaa58962458/article/details/120764754
  76. @PostMapping("downloadCreative")
  77. public Result downloadCreative(@RequestParam("minioObjectId") Integer minioObjectId, HttpServletResponse response) throws Exception {
  78. Result result = new Result();
  79. if (minioObjectId == null) {
  80. result.setMessage("文件id为空");
  81. return result;
  82. }
  83. MinioObject minioObjectById = minioObjectService.getMinioObjectById(minioObjectId);
  84. String bucketName = minioObjectById.getBucketName();
  85. String name = minioObjectById.getName();
  86. boolean exists = minIOUtils.bucketExists(bucketName);
  87. //桶不存在
  88. if (!exists) {
  89. result.setMessage("桶不存在");
  90. return result;
  91. }
  92. boolean objectExist = minIOUtils.isObjectExist(bucketName, name);
  93. if (!objectExist) {
  94. result.setMessage("文件不存在");
  95. return result;
  96. }
  97. // 获取外链,链接失效时间7天
  98. String url = minIOUtils.getPresignedObjectUrl(bucketName, name);
  99. result.setData(url);
  100. return result;
  101. }
  102. }

Vue前端上传

  1. <el-upload
  2. class="upload-demo"
  3. :action="url+uploadUrl"
  4. :on-change="handleChange"
  5. :file-list="fileList"
  6. name="file"
  7. >
  8. <el-button size="small" type="primary">点击上传</el-button>
  9. </el-upload>
  10. data() {
  11. return {
  12. url: request.defaults.baseURL,
  13. uploadUrl: '/minio/uploadCreative',
  14. }
  15. }

Vue下载,后端生成外链实现下载

  1. <el-button
  2. size="small"
  3. type="primary"
  4. style="margin-left: 15px"
  5. @click="creativeScriptDownload(props.row.creativeScript)"
  6. >点击下载
  7. </el-button>
  8. creativeScriptDownload: function(creativeScript) {
  9. request.post('/minio/downloadCreative?minioObjectId=' + creativeScript).then(res => {
  10. window.open(res.data)
  11. }).catch(err => {
  12. this.$message({
  13. type: 'info',
  14. message: '创意脚本下载失败' + err.message
  15. })
  16. })
  17. }

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

闽ICP备14008679号