Minio 整合springboot 开发 实现文件上传

Minio 作为对象存储,灵活方便,结合java 实现minio 文件上传

1.搭建maven环境,添加依赖包

<properties>    <minio.version>4.0.0</minio.version></properties>
<dependency>    <groupId>io.minio</groupId>    <artifactId>minio</artifactId>    <version>${minio.version}</version></dependency>2.书写一个MinioUtils
public class MinioClientUtils {

private static final Logger LOGGER = LoggerFactory.getLogger(MinioClientUtils.class);

private static MinioClientUtils minioClientUtils;

private MinioClient minioClient;

private static int RETRY_NUM = 3;

private static final String bucketPublicPolicy = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Action\":[\"s3:GetBucketLocation\",\"s3:ListBucket\",\"s3:ListBucketMultipartUploads\"],\"Effect\":\"Allow\",\"Principal\":{\"AWS\":[\"*\"]},\"Resource\":[\"arn:aws:s3:::test\"],\"Sid\":\"\"},{\"Action\":[\"s3:AbortMultipartUpload\",\"s3:DeleteObject\",\"s3:GetObject\",\"s3:ListMultipartUploadParts\",\"s3:PutObject\"],\"Effect\":\"Allow\",\"Principal\":{\"AWS\":[\"*\"]},\"Resource\":[\"arn:aws:s3:::test/*\"],\"Sid\":\"\"}]}";

public static MinioClientUtils getInstance() {        if (null != minioClientUtils) {            return minioClientUtils;        }        synchronized (MinioClientUtils.class) {            if (null == minioClientUtils) {                minioClientUtils = new MinioClientUtils();            }        }        return minioClientUtils;    }

private MinioClientUtils() {        init();    }

private void init() {        final Configuration configuration = initConfiguration();        String url = configuration.getString("minio.url", StringUtils.EMPTY);        String username = configuration.getString("minio.name", StringUtils.EMPTY);        String password = configuration.getString("minio.password", StringUtils.EMPTY);        String region = configuration.getString("minio.region", StringUtils.EMPTY);        try {            if (StringUtils.isNotEmpty(url) && StringUtils.isNotEmpty(username) && StringUtils.isNotEmpty(password)) {                minioClient = new MinioClient(url, username, password, false);            }        } catch (Exception e) {            LOGGER.error("restClient.close occur error", e);        }

}

public boolean createBucketPublic(String bucketName) {        boolean isCreated;        try {//            if (minioClient.bucketExists(bucketName)) {//                isCreated = false;//            }            minioClient.makeBucket("buzi");            //minioClient.setBucketPolicy(bucketName, bucketPublicPolicy);            isCreated = true;        } catch (Exception e) {            isCreated = false;            LOGGER.error("createBucketPublic", e);            e.printStackTrace();        }        return isCreated;    }

public String uploadJpegFile(String bucketName, String minioPath, String jpgFilePath) {        return uploadFile(bucketName, minioPath, jpgFilePath, MediaType.IMAGE_JPEG_VALUE);    }

public String uploadJpegStream(String bucketName, String minioPath, InputStream inputStream) {        return uploadStream(bucketName, minioPath, inputStream, MediaType.IMAGE_JPEG_VALUE);    }

public String uploadStream(String bucketName, String minioFilePath, InputStream inputStream, String mediaType) {        LOGGER.info("uploadStream for bucketName={} minioFilePath={} inputStream.getclass={}, mediaType={}", bucketName,                minioFilePath, inputStream.getClass(), mediaType);        if (StringUtils.isBlank(mediaType)) {            mediaType = MediaType.APPLICATION_OCTET_STREAM_VALUE;        }        try {            putObjectWithRetry(bucketName, minioFilePath, inputStream, mediaType);            return cleanUrlByRemoveIp(minioClient.getObjectUrl(bucketName, minioFilePath));        } catch (Exception e) {            LOGGER.error("uploadStream occur error:", e);            throw new RuntimeException(e);        }    }

public String uploadFile(String bucketName, String minioFilePath, String localFile, String mediaType) {        LOGGER.info("uploadFile for bucketName={} minioFilePath={} localFile={}, mediaType={}", bucketName,                minioFilePath, localFile, mediaType);        if (StringUtils.isBlank(mediaType)) {            mediaType = MediaType.APPLICATION_OCTET_STREAM_VALUE;        }        try {            putObjectWithRetry(bucketName, minioFilePath, localFile, mediaType);            return cleanUrlByRemoveIp(minioClient.getObjectUrl(bucketName, minioFilePath));        } catch (Exception e) {            LOGGER.error("uploadFile occur error:", e);            throw new RuntimeException(e);        }    }

public List<MinioEntity> listFilesSwap(String bucketName, String prefix, boolean recursive) {        LOGGER.info("list files for bucketName={} prefix={} recursive={}", bucketName, prefix, recursive);        return swapResultToEntityList(minioClient.listObjects(bucketName, prefix, recursive));    }

public Iterable<Result<Item>> listFiles(String bucketName, String prefix, boolean recursive) {        LOGGER.info("list files for bucketName={} prefix={} recursive={}", bucketName, prefix, recursive);        return minioClient.listObjects(bucketName, prefix, recursive);    }

public List<MinioEntity> listFilesByBucketNameSwap(String bucketName) {        LOGGER.info("listFilesByBucketName for bucketName={}", bucketName);        return swapResultToEntityList(minioClient.listObjects(bucketName, null, true));    }

public Iterable<Result<Item>> listFilesByBucketName(String bucketName) {        LOGGER.info("listFilesByBucketName for bucketName={}", bucketName);        return minioClient.listObjects(bucketName, null, true);    }

public Iterable<Result<Item>> listFilesByBucketAndPrefix(String bucketName, String prefix) {        LOGGER.info("listFilesByBucketAndPrefix for bucketName={} and prefix={}", bucketName, prefix);        return minioClient.listObjects(bucketName, prefix, true);    }

public List<MinioEntity> listFilesByBucketAndPrefixSwap(String bucketName, String prefix) {        LOGGER.info("listFilesByBucketAndPrefix for bucketName={} and prefix={}", bucketName, prefix);        return swapResultToEntityList(minioClient.listObjects(bucketName, prefix, true));    }

private Configuration initConfiguration() {        ClassLoader classLoader = MinioClientUtils.class.getClassLoader();        if (null == classLoader) {            classLoader = Thread.currentThread().getContextClassLoader();        }

Configuration configuration = null;        URL resource = classLoader.getResource("minio.properties");        if (null == resource) {            LOGGER.error("can not find minio.properties");            throw new RuntimeException("can not find minio.properties");        }        try {            configuration = new PropertiesConfiguration(resource);        } catch (ConfigurationException e) {            LOGGER.error("load properties from url={} occur error", resource.toString());            throw new RuntimeException("load properties from url=" + resource.toString() + " occur error", e);        }        return configuration;    }

private MinioEntity swapResultToEntity(Result<Item> result) {        MinioEntity minioEntity = new MinioEntity();        try {            if (result.get() != null) {                Item item = result.get();                minioEntity.setObjectName(cleanUrlByRemoveIp(item.objectName()));                minioEntity.setDir(item.isDir());                minioEntity.setEtag(item.etag());                minioEntity.setLastModified(item.lastModified());                minioEntity.setSize(item.size());                minioEntity.setStorageClass(item.storageClass());            }        } catch (Exception e) {            LOGGER.error("UrlUtils error, e={}", e.getMessage());        }        return minioEntity;    }

private List<MinioEntity> swapResultToEntityList(Iterable<Result<Item>> results) {        List<MinioEntity> minioEntities = new ArrayList<>();        for (Result<Item> result : results) {            minioEntities.add(swapResultToEntity(result));        }        return minioEntities;    }

public void putObjectWithRetry(String bucketName, String objectName, InputStream stream, String contentType) throws IOException, InvalidKeyException, NoSuchAlgorithmException, InsufficientDataException, InvalidArgumentException, NoResponseException, InvalidBucketNameException, XmlPullParserException, InternalException {        int current = 0;        boolean isSuccess = false;        while (!isSuccess && current < RETRY_NUM) {            try {                minioClient.putObject(bucketName, objectName, stream, contentType);                isSuccess = true;            } catch (ErrorResponseException e) {                LOGGER.warn("[minio] putObject stream, ErrorResponseException occur for time =" + current, e);                current++;            }        }        if (current == RETRY_NUM) {            LOGGER.error("[minio] putObject, backetName={}, objectName={}, failed finally!");        }    }

public void putObjectWithRetry(String bucketName, String objectName, String fileName, String contentType) throws InvalidBucketNameException, NoSuchAlgorithmException, InsufficientDataException, IOException, InvalidKeyException, NoResponseException, XmlPullParserException, ErrorResponseException, InternalException, InvalidArgumentException, InsufficientDataException {        int current = 0;        boolean isSuccess = false;        while (!isSuccess && current < RETRY_NUM) {            try {                minioClient.putObject(bucketName, objectName, fileName, contentType);                isSuccess = true;            } catch (ErrorResponseException e) {                current++;                LOGGER.debug("[minio] putObject file, ErrorResponseException occur!");            }        }        if (current == RETRY_NUM) {            LOGGER.error("[minio] putObject, backetName={}, objectName={}, failed finally!");        }    }

public static void main(String[] args) {        MinioClientUtils.getInstance().createBucketPublic("helo");    }

}
 
}3.工具类已经封装各种上传。4.public void upload(@RequestParam("file") MulipartFile data,String bucketName,String path){String fileName = data.getOriginalFilename();String filePath = path+"/"+fileName;String contentType = data.getContentType();InputStream inputStram = data.getInputStream();MinioClientUtils minioClientUtils = MinioCLinetUtils.getInstance();
minioClientUtils.uploadStream(
bucketName,
filePath,inputStream,contentType
);
}

原文地址:https://www.cnblogs.com/cxdxm/p/9061413.html

时间: 2024-10-10 07:42:42

Minio 整合springboot 开发 实现文件上传的相关文章

springboot框架,文件上传问题===org.springframework.web.HttpMediaTypeNotSupportedException: Content type &#39;multipart/form-data;

使用IDEA开发springboot项目,需求中要提交数据项和文件上传,同时接收实体bean对象和文件,后台Controller接收配置方式: Controller代码如下: 1 @RequestMapping(value="/comment",method = RequestMethod.POST) 2 public @ResponseBody RetResult saveIndustryComment(HttpServletRequest request,@RequestParam

IOS开发之文件上传

IOS开发之文件上传 在移动应用开发  文件形式上传是必不可少的,最近把IOS这块文件上传文件代码简单的整理一下,如果大家有需要安卓这边的代码,本人也可以分享给大家!QQ群:74432915  欢迎大家一起探讨 首先本demo采用网上开源框架 AFNetworking  源码:http://download.csdn.net/detail/wangliang198901/7809439 将整个框架导入IOS新建立的工程中 在FKAppDelegate.h声明 如下: #import <UIKit

Springboot如何启用文件上传功能

网上的文章在写 "springboot文件上传" 时,都让你加上模版引擎,我只想说,我用不上,加模版引擎,你是觉得我脑子坏了,还是觉得我拿不动刀了. springboot如何启用文件上传功能: 其实你啥都不用做,直接用就是了.文件上传相关的随着你的webStarter引入,就被引入到你的项目里面了. POM依赖: 代码: 注意事项: springboot文件上传 单个请求包含的文件默认大小:1MB-10MB 请求格式POST 参数格式form-data 如果出错了,请仔细查看报错信息!

04springMVC结构,mvc模式,spring-mvc流程,spring-mvc的第一个例子,三种handlerMapping,几种控制器,springmvc基于注解的开发,文件上传,拦截器,s

 1. Spring-mvc介绍 1.1市面上流行的框架 Struts2(比较多) Springmvc(比较多而且属于上升的趋势) Struts1(即将被淘汰) 其他 1.2  spring-mvc结构 DispatcherServlet:中央控制器,把请求给转发到具体的控制类 Controller:具体处理请求的控制器(配置文件方式需要配置,注解方式不用配置) handlerMapping:映射处理器,负责映射中央处理器转发给controller时的映射策略 ModelAndView:服务

SpringBoot: 6.文件上传(转)

1.编写页面uploadFile.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>上传文件</title> </head> <body> <form action="uploadFile" method="post" enct

Eclipse搭建springboot项目(三)文件上传

知识点:SpringBoot2.x文件上传:HTML页面文件上传和后端处理 1.springboot文件上传 MultipartFile file,源自SpringMVC 1)静态页面直接访问:localhost:8080/index.html 注意点:如果想要直接访问html页面,则需要把html放在springboot默认加载的文件夹下面 2)MultipartFile 对象的transferTo方法,用于文件保存(效率和操作比原先用FileOutStream方便和高效) 访问路径 http

springboot+vue实现文件上传

https://blog.csdn.net/mqingo/article/details/84869841 技术: 后端:springboot 前端框架:vue 数据库:mysql pom.xml: <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.3</versi

Java Web开发之文件上传

文件上传有SmartUpload.Apache的Commons fileupload.我们今天介绍Commons fileupload的用法. 1.commons-io.jar 和commons-fileupload-1.3.1.jar 下载地址:http://pan.baidu.com/s/1kVtYMzH 2.web.xml 1 <!-- 上传文件 服务器端 --> 2 <servlet> 3 <servlet-name>UploadServlet</serv

iOS开发 - 封装文件上传工具类

文件上传的步骤 1.设置请求头 * 目的:告诉服务器请求体里面的内容并非普通的参数,而是包含了文件参数 [request setValue:@"multipart/form-data; boundary=maljob" forHTTPHeaderField:@"Content-Type"]; 2.设置请求体 * 作用:存放参数(文件参数和非文件参数) 1> 非文件参数 [body appendData:MalJobEncode(@"--maljob\