1.安装minio

这里采用docker进行安装。

搜索该镜像:docker search minio

找到了镜像:minio/minio

拉取镜像:docker pull minio/minio

启动镜像:

docker run --name minio -p 9090:9000 -p 9999:9999 -d \
--restart=always -e \
"MINIO_ROOT_USER=minioadmin" \
-e "MINIO_ROOT_PASSWORD=minioadmin123?" \
-v /home/minio/data:/data \
-v /home/minio/config:/root/.minio minio/minio server /data --console-address '0.0.0.0:9999'

浏览器访问minio的控制台:

http://ip:port

访问到网页如下:

2.配置minio

1.创建一个放图片的目录

登录网页进去:

点击左侧Buckets页面,然后点击右边的 Create Bucket 去创建一个目录,这个目录,如下,我创建了一个imgs,这个目录用来放上传的图片,需要记住这个目录,代码里面需要用

2.创建上传文件需要的key

需要把这两个key复制出来,代码里面需要用,就相当于账户密码之类的

3.springboot整合minio

1. 导入maven

        <!--minio--><dependency><groupId>io.minio</groupId><artifactId>minio</artifactId><version>8.2.1</version></dependency>

2.配置yml文件

# minio文件系统配置
minio:# minio配置的地址,端口9090url: http://xxx.xx.xx.xx:9090# 账号accessKey: RKGZKAUGHKDY0XVN# 密码secretKey: HmTlAJoll7V0OjfBoyKmsIGF# MinIO桶名字bucketName: imgs

3.代码部分

MinioUtil.java
package com.tn.humanenv.common.utils;import io.minio.*;
import io.minio.messages.DeleteError;
import io.minio.messages.DeleteObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.multipart.MultipartFile;import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.stream.Collectors;/*** minio存储*/
@Component
public class MinioUtil {@Autowiredprivate MinioClient minioClient;/*** @author xhw* @生成文件名* @param fileName* @return*/public String getUUIDFileName(String fileName) {int idx = fileName.lastIndexOf(".");String extention = fileName.substring(idx);String newFileName = DateUtils.getDateTo_().replace("-","")+UUID.randomUUID().toString().replace("-","")+extention;return newFileName;}/*** 查看存储bucket是否存在** @param bucketName 存储bucket* @return boolean*/public Boolean bucketExists(String bucketName) {Boolean found;try {found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());} catch (Exception e) {e.printStackTrace();return false;}return found;}/*** 创建存储bucket** @param bucketName 存储bucket名称* @return Boolean*/public Boolean makeBucket(String bucketName) {try {minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());} catch (Exception e) {e.printStackTrace();return false;}return true;}/*** 删除存储bucket** @param bucketName 存储bucket名称* @return Boolean*/public Boolean removeBucket(String bucketName) {try {minioClient.removeBucket(RemoveBucketArgs.builder().bucket(bucketName).build());} catch (Exception e) {e.printStackTrace();return false;}return true;}/*** 文件上传** @param file       文件* @param bucketName 存储bucket* @return Boolean*/public Boolean upload(MultipartFile file, String fileName, String bucketName) {try {PutObjectArgs objectArgs = PutObjectArgs.builder().bucket(bucketName).object(fileName).stream(file.getInputStream(), file.getSize(), -1).contentType(file.getContentType()).build();//文件名称相同会覆盖minioClient.putObject(objectArgs);} catch (Exception e) {e.printStackTrace();return false;}return true;}/*** 文件下载** @param bucketName 存储bucket名称* @param fileName   文件名称* @param res        response* @return Boolean*/public void download(String bucketName, String fileName, HttpServletResponse res) {GetObjectArgs objectArgs = GetObjectArgs.builder().bucket(bucketName).object(fileName).build();try (GetObjectResponse response = minioClient.getObject(objectArgs)) {byte[] buf = new byte[1024];int len;try (FastByteArrayOutputStream os = new FastByteArrayOutputStream()) {while ((len = response.read(buf)) != -1) {os.write(buf, 0, len);}os.flush();byte[] bytes = os.toByteArray();res.setCharacterEncoding("utf-8");//设置强制下载不打开res.setContentType("application/force-download");res.addHeader("Content-Disposition", "attachment;fileName=" + fileName);try (ServletOutputStream stream = res.getOutputStream()) {stream.write(bytes);stream.flush();}}} catch (Exception e) {e.printStackTrace();}}/*** 查看文件对象** @param bucketName 存储bucket名称* @return 存储bucket内文件对象信息*/
/*    public List<ObjectItem> listObjects(String bucketName) {Iterable<Result<Item>> results = minioClient.listObjects(ListObjectsArgs.builder().bucket(bucketName).build());List<ObjectItem> objectItems = new ArrayList<>();try {for (Result<Item> result : results) {Item item = result.get();ObjectItem objectItem = new ObjectItem();objectItem.setObjectName(item.objectName());objectItem.setSize(item.size());objectItems.add(objectItem);}} catch (Exception e) {e.printStackTrace();return null;}return objectItems;}*//*** 批量删除文件对象** @param bucketName 存储bucket名称* @param objects    对象名称集合*/public Iterable<Result<DeleteError>> removeObjects(String bucketName, List<String> objects) {List<DeleteObject> dos = objects.stream().map(e -> new DeleteObject(e)).collect(Collectors.toList());Iterable<Result<DeleteError>> results = minioClient.removeObjects(RemoveObjectsArgs.builder().bucket(bucketName).objects(dos).build());return results;}
}
SysFileController.java
package com.tn.humanenv.controller;import com.tn.humanenv.common.controller.BaseController;
import com.tn.humanenv.common.domain.AjaxResult;
import com.tn.humanenv.common.utils.StringUtils;
import com.tn.humanenv.service.SysFileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;import java.util.Map;/*** @author xhw* @desc 文件上传* @date 2022/09/04*/
@RestController
@RequestMapping("/file")
public class SysFileController extends BaseController {@Autowiredprivate SysFileService sysFileService;/*** 图片上传minio** @param file 图片文件* @return 返回*/@RequestMapping(value = "/upload", method = RequestMethod.POST)public AjaxResult uploadFileMinio(MultipartFile file) {Map<String,Object> map = sysFileService.uploadFileMinio(file);if (StringUtils.isNotNull(map)) {return AjaxResult.success(map);}return error("上传失败");}}
SysFileServiceImpl.java
package com.tn.humanenv.service.Impl;import com.tn.humanenv.common.config.MinioConfig;
import com.tn.humanenv.common.utils.MinioUtil;
import com.tn.humanenv.service.SysFileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;import java.util.HashMap;
import java.util.Map;@Service
public class SysFileServiceImpl implements SysFileService {@Autowiredprivate MinioConfig minioConfig;@Autowiredprivate MinioUtil minioUtil;@Overridepublic Map<String,Object> uploadFileMinio(MultipartFile file) {boolean flag = false;if (file.isEmpty()) {throw new RuntimeException("文件不存在!");}// 判断存储桶是否存在if (!minioUtil.bucketExists(minioConfig.getBucketName())) {minioUtil.makeBucket(minioConfig.getBucketName());}// 生成文件名String newFileName = minioUtil.getUUIDFileName(file.getOriginalFilename());try {// 上传文件flag = minioUtil.upload(file, newFileName, minioConfig.getBucketName());} catch (Exception e) {return null;}// 判断是否上传成功,成功就返回url,不成功就返回nullMap<String,Object> map = new HashMap<>();map.put("url",minioConfig.getUrl() + "/" + minioConfig.getBucketName() + "/" + newFileName);map.put("fileName",newFileName);if (flag){return map;}return null;}
}
SysFileService.java
package com.tn.humanenv.service;import org.springframework.web.multipart.MultipartFile;import java.util.Map;public interface SysFileService {public Map<String,Object> uploadFileMinio(MultipartFile file);
}
MinioConfig.java
package com.tn.humanenv.common.config;import io.minio.MinioClient;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;@Configuration
@ConfigurationProperties(prefix = "minio")
public class MinioConfig {/*** 服务地址*/public String url;/*** 用户名*/public String accessKey;/*** 密码*/public String secretKey;/*** 存储桶名称*/public String bucketName;// "如果是true,则用的是https而不是http,默认值是true"public static Boolean secure = false;public String getUrl() {return url;}public void setUrl(String url) {this.url = url;}public String getAccessKey() {return accessKey;}public void setAccessKey(String accessKey) {this.accessKey = accessKey;}public String getSecretKey() {return secretKey;}public void setSecretKey(String secretKey) {this.secretKey = secretKey;}public String getBucketName() {return bucketName;}public void setBucketName(String bucketName) {this.bucketName = bucketName;}public static Boolean getSecure() {return secure;}public static void setSecure(Boolean secure) {MinioConfig.secure = secure;}@Beanpublic MinioClient getMinioClient() {return MinioClient.builder().endpoint(url).credentials(accessKey, secretKey).build();}
}

4.测试上传图片

调用接口如下:

把链接拿出来浏览器访问如下:

上传excel文件如下:

访问该地址,直接就下载了这个excel文件:

如上。

springboot整合minio上传文件相关推荐

  1. MinIO入门-02 SpringBoot 整合MinIO并实现文件上传

    SpringBoot 整合MinIO并实现文件上传 1.依赖 <!-- https://mvnrepository.com/artifact/io.minio/minio --> < ...

  2. springboot使用ajax上传文件

    SpringBoot使用Ajax上传文件 接上一个上传文件操作 上次使用的是from表单进行提交 这次我们使用ajax进行提交 地址在这儿:springboot上传文件 上次controller层已经 ...

  3. SpringBoot MultipartFile 监控上传文件进度

    # SpringBoot MultipartFile监控上传文件进度>引用块内容 在一次项目中需要监控文件上传的进度.将进度监控到之后计算百分比,存入session中session需要配置实时生 ...

  4. SpringBoot+El-upload实现上传文件到通用上传接口并返回文件全路径(若依前后端分离版源码分析)

    场景 SpringBoot+ElementUI实现通用文件下载请求(全流程图文详细教程): https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/deta ...

  5. SpringBoot设置全局上传文件路径并上传文件

    前言 在后端处理文件上传的时候,我们通上传文件的时候,一般这个路径不会随便写. 比如这篇文章中的路径:解决SpringBoot文件上传报错:org.apache.tomcat.util.http.fi ...

  6. springboot urlresource_Spring Boot上传文件+部署到Tomcat

    1 概述 Spring Boot上传文件,根据官方uploadfile示例修改的,可以打成war放到服务器上(笔者使用的是Tomcat).主要步骤是创建异常类,属性类,接口类与控制器类,最后进行少量修 ...

  7. minio 上传文件失败报错信息: The difference between the request time and the server‘s time is too large.

    问题描述: MINIO上传失败,错误信息如下: The difference between the request time and the server's time is too large. ...

  8. Springboot通过SFTP上传文件到服务器

    流程是这样的: 前端选择文件上传-------->调用后台接口,后台连接服务器(Linux)--------->上传成功  前端无论是通过ajax,还是form表单直接提交都可以,这里暂时 ...

  9. springboot使用ServletFileUpload上传文件

    前端 upload.html <HTML> <HEAD><title>上传文件</title> </HEAD> <body> & ...

最新文章

  1. linux中的apachectl是什么命令
  2. python闭包锁住女神的心
  3. 企业组织机构代码验证JavaScript版和Java版 - 修正版V20090214
  4. cocos2dx 3.x 解决输入框(TextField,TextFieldTTF) 输入中文变乱码的问题
  5. python 修改文件属性 macos_Python中用MacFSEvents模块监视MacOS文件系统改变一例
  6. 140:Bandwidth
  7. 学习C++项目——select模型,poll模型和epoll模型
  8. 博后招募 | 香港中文大学招收机器人视觉智能传感方向博士后/RA/访问学者
  9. java删除某些段落word_Java 批量删除Word中的空白段落
  10. 北京中医药大学计算机应用基础作业,北京中医药大学计算机应用基础第五次.doc...
  11. 18年下半年读书清单一览
  12. Scala中特质的使用以及特质冲突
  13. 类似安卓的点9图片,气泡图片调成自己需要的
  14. 用python编写万年历
  15. vi两个文件之间复制
  16. 针对《评人工智能如何走向新阶段》一文,继续发布国内外的跟贴留言503-531条如下:
  17. 计算机视觉中的自监督学习与注意力建模
  18. 记录第一次ANN跑BCI Competition iv 2a过程
  19. uni-app app 跳转 微信小程序(安卓/ios)
  20. 论文查重时封面、目录、引用会检测吗?

热门文章

  1. Android仿今日头条的开源项目
  2. python安装及环境配置
  3. 欢迎来到天蓝零度的官方微博发布平台
  4. 一夜狼人杀:千万不要沉默不语,参与游戏聊自己的角色
  5. 凤姐都在理财了,你在干什么?
  6. 修改注册表,更改Win10版本,解决升级时无法“保留个人文件和应用”的问题
  7. eslint报错解决方案:--fix的使用
  8. stm32的点亮led的基础知识
  9. 2020年8月20计算机大赛,NOI2020于8月17日正式开幕!今年哪些竞赛选手被保送清北计算机专业?...
  10. 如何在靠tiktok在三个月内快速赚到20w的?实现人生逆转