首先pom文件引入相关依赖
<!--minio--> <dependency> <groupid>io.minio</groupid> <artifactid>minio</artifactid> <version>3.0.10</version> </dependency>
springboot配置文件application.yml 里配置minio信息
#minio配置minio: endpoint: http://${minio_host:172.16.10.21}:9000/ accesskey: ${minio_user:minioadmin} secretkey: ${minio_pwd:minioadmin} bucket: ${minio_space:spacedata} http-url: http://${minio_url:172.16.10.21}:9000/ imgsize: 10485760 filesize: 1048576000
创建minioitem字段项目类
import io.minio.messages.item;import io.minio.messages.owner;import io.swagger.annotations.apimodelproperty;import lombok.data; import java.util.date; @datapublic class minioitem { /**对象名称**/ @apimodelproperty("对象名称") private string objectname; /**最后操作时间**/ @apimodelproperty("最后操作时间") private date lastmodified; private string etag; /**对象大小**/ @apimodelproperty("对象大小") private string size; private string storageclass; private owner owner; /**对象类型:directory(目录)或file(文件)**/ @apimodelproperty("对象类型:directory(目录)或file(文件)") private string type; public minioitem(string objectname, date lastmodified, string etag, string size, string storageclass, owner owner, string type) { this.objectname = objectname; this.lastmodified = lastmodified; this.etag = etag; this.size = size; this.storageclass = storageclass; this.owner = owner; this.type = type; } public minioitem(item item) { this.objectname = item.objectname(); this.type = item.isdir() ? "directory" : "file"; this.etag = item.etag(); long sizenum = item.objectsize(); this.size = sizenum > 0 ? convertfilesize(sizenum):"0"; this.storageclass = item.storageclass(); this.owner = item.owner(); try { this.lastmodified = item.lastmodified(); }catch(nullpointerexception e){} } public string convertfilesize(long size) { long kb = 1024; long mb = kb * 1024; long gb = mb * 1024; if (size >= gb) { return string.format("%.1f gb", (float) size / gb); } else if (size >= mb) { float f = (float) size / mb; return string.format(f > 100 ? "%.0f mb" : "%.1f mb", f); } else if (size >= kb) { float f = (float) size / kb; return string.format(f > 100 ? "%.0f kb" : "%.1f kb", f); } else{ return string.format("%d b", size); } }}
创建miniotemplate模板类
import com.gis.spacedata.domain.dto.minio.minioitem;import com.google.common.collect.lists;import io.minio.minioclient;import io.minio.objectstat;import io.minio.result;import io.minio.errors.*;import io.minio.messages.bucket;import io.minio.messages.item;import lombok.requiredargsconstructor;import lombok.sneakythrows;import lombok.extern.slf4j.slf4j;import org.apache.commons.lang3.stringutils;import org.springframework.beans.factory.initializingbean;import org.springframework.beans.factory.annotation.value;import org.springframework.http.httpheaders;import org.springframework.http.httpstatus;import org.springframework.http.responseentity;import org.springframework.stereotype.component;import org.springframework.util.filecopyutils;import org.xmlpull.v1.xmlpullparserexception; import javax.servlet.http.httpservletrequest;import java.io.file;import java.io.ioexception;import java.io.inputstream;import java.io.unsupportedencodingexception;import java.net.url;import java.net.urlencoder;import java.nio.charset.standardcharsets;import java.security.invalidkeyexception;import java.security.nosuchalgorithmexception;import java.util.arraylist;import java.util.list;import java.util.optional; @slf4j@component@requiredargsconstructorpublic class miniotemplate implements initializingbean { /** * minio的路径 **/ @value("${minio.endpoint}") private string endpoint; /** * minio的accesskey **/ @value("${minio.accesskey}") private string accesskey; /** * minio的secretkey **/ @value("${minio.secretkey}") private string secretkey; /** * 下载地址 **/ @value("${minio.http-url}") private string httpurl; @value("${minio.bucket}") private string bucket; private static minioclient minioclient; @override public void afterpropertiesset() throws exception { minioclient = new minioclient(endpoint, accesskey, secretkey); } @sneakythrows public boolean bucketexists(string bucketname) { return minioclient.bucketexists(bucketname); } /** * 创建bucket * * @param bucketname bucket名称 */ @sneakythrows public void createbucket(string bucketname) { if (!bucketexists(bucketname)) { minioclient.makebucket(bucketname); } } /** * 获取全部bucket * <p> * https://docs.minio.io/cn/java-client-api-reference.html#listbuckets */ @sneakythrows public list<bucket> getallbuckets() { return minioclient.listbuckets(); } /** * 根据bucketname获取信息 * * @param bucketname bucket名称 */ @sneakythrows public optional<bucket> getbucket(string bucketname) { return minioclient.listbuckets().stream().filter(b -> b.name().equals(bucketname)).findfirst(); } /** * 根据bucketname删除信息 * * @param bucketname bucket名称 */ @sneakythrows public void removebucket(string bucketname) { minioclient.removebucket(bucketname); } /** * 根据文件前缀查询文件 * * @param bucketname bucket名称 * @param prefix 前缀 * @param recursive 是否递归查询 * @return minioitem 列表 */ @sneakythrows public list<minioitem> getallobjectsbyprefix(string bucketname, string prefix, boolean recursive) { list<minioitem> objectlist = new arraylist<>(); iterable<result<item>> objectsiterator = minioclient.listobjects(bucketname, prefix, recursive); for (result<item> result : objectsiterator) { objectlist.add(new minioitem(result.get())); } return objectlist; } /** * 获取文件外链 * * @param bucketname bucket名称 * @param objectname 文件名称 * @param expires 过期时间 <=7 * @return url */ @sneakythrows public string getobjecturl(string bucketname, string objectname, integer expires) { return minioclient.presignedgetobject(bucketname, objectname, expires); } /** * 获取文件外链 * * @param bucketname bucket名称 * @param objectname 文件名称 * @return url */ @sneakythrows public string getobjecturl(string bucketname, string objectname) { return minioclient.presignedgetobject(bucketname, objectname); } /** * 获取文件url地址 * * @param bucketname bucket名称 * @param objectname 文件名称 * @return url */ @sneakythrows public string getobjecturl(string bucketname, string objectname) { return minioclient.getobjecturl(bucketname, objectname); } /** * 获取文件 * * @param bucketname bucket名称 * @param objectname 文件名称 * @return 二进制流 */ @sneakythrows public inputstream getobject(string bucketname, string objectname) { return minioclient.getobject(bucketname, objectname); } /** * 上传文件(流下载) * * @param bucketname bucket名称 * @param objectname 文件名称 * @param stream 文件流 * @throws exception https://docs.minio.io/cn/java-client-api-reference.html#putobject */ public void putobject(string bucketname, string objectname, inputstream stream) throws exception { string contenttype = "application/octet-stream"; if ("json".equals(objectname.split("\\.")[1])) { //json格式,c++编译生成文件,需要直接读取 contenttype = "application/json"; } minioclient.putobject(bucketname, objectname, stream, stream.available(), contenttype); } /** * 上传文件 * * @param bucketname bucket名称 * @param objectname 文件名称 * @param stream 文件流 * @param size 大小 * @param contexttype 类型 * @throws exception https://docs.minio.io/cn/java-client-api-reference.html#putobject */ public void putobject(string bucketname, string objectname, inputstream stream, long size, string contexttype) throws exception { minioclient.putobject(bucketname, objectname, stream, size, contexttype); } /** * 获取文件信息 * * @param bucketname bucket名称 * @param objectname 文件名称 * @throws exception https://docs.minio.io/cn/java-client-api-reference.html#statobject */ public objectstat getobjectinfo(string bucketname, string objectname) throws exception { return minioclient.statobject(bucketname, objectname); } /** * 删除文件夹及文件 * * @param bucketname bucket名称 * @param objectname 文件或文件夹名称 * @since tarzan liu */ public void removeobject(string bucketname, string objectname) { try { if (stringutils.isnotblank(objectname)) { if (objectname.endswith(".") || objectname.endswith("/")) { iterable<result<item>> list = minioclient.listobjects(bucketname, objectname); list.foreach(e -> { try { minioclient.removeobject(bucketname, e.get().objectname()); } catch (invalidbucketnameexception invalidbucketnameexception) { invalidbucketnameexception.printstacktrace(); } catch (nosuchalgorithmexception nosuchalgorithmexception) { nosuchalgorithmexception.printstacktrace(); } catch (insufficientdataexception insufficientdataexception) { insufficientdataexception.printstacktrace(); } catch (ioexception ioexception) { ioexception.printstacktrace(); } catch (invalidkeyexception invalidkeyexception) { invalidkeyexception.printstacktrace(); } catch (noresponseexception noresponseexception) { noresponseexception.printstacktrace(); } catch (xmlpullparserexception xmlpullparserexception) { xmlpullparserexception.printstacktrace(); } catch (errorresponseexception errorresponseexception) { errorresponseexception.printstacktrace(); } catch (internalexception internalexception) { internalexception.printstacktrace(); } }); } } } catch (xmlpullparserexception e) { e.printstacktrace(); } } /** * 下载文件夹内容到指定目录 * * @param bucketname bucket名称 * @param objectname 文件或文件夹名称 * @param dirpath 指定文件夹路径 * @since tarzan liu */ public void downloadtargetdir(string bucketname, string objectname, string dirpath) { try { if (stringutils.isnotblank(objectname)) { if (objectname.endswith(".") || objectname.endswith("/")) { iterable<result<item>> list = minioclient.listobjects(bucketname, objectname); list.foreach(e -> { try { string url = minioclient.getobjecturl(bucketname, e.get().objectname()); getfile(url, dirpath); } catch (invalidbucketnameexception invalidbucketnameexception) { invalidbucketnameexception.printstacktrace(); } catch (nosuchalgorithmexception nosuchalgorithmexception) { nosuchalgorithmexception.printstacktrace(); } catch (insufficientdataexception insufficientdataexception) { insufficientdataexception.printstacktrace(); } catch (ioexception ioexception) { ioexception.printstacktrace(); } catch (invalidkeyexception invalidkeyexception) { invalidkeyexception.printstacktrace(); } catch (noresponseexception noresponseexception) { noresponseexception.printstacktrace(); } catch (xmlpullparserexception xmlpullparserexception) { xmlpullparserexception.printstacktrace(); } catch (errorresponseexception errorresponseexception) { errorresponseexception.printstacktrace(); } catch (internalexception internalexception) { internalexception.printstacktrace(); } }); } } } catch (xmlpullparserexception e) { e.printstacktrace(); } } public static void main(string[] args) throws nosuchalgorithmexception, ioexception, invalidkeyexception, xmlpullparserexception { try { // 使用minio服务的url,端口,access key和secret key创建一个minioclient对象 minioclient minioclient = new minioclient("http://172.16.10.201:9000/", "minioadmin", "minioadmin"); // 检查存储桶是否已经存在 boolean isexist = minioclient.bucketexists("spacedata"); if (isexist) { system.out.println("bucket already exists."); } else { // 创建一个名为asiatrip的存储桶,用于存储照片的zip文件。 minioclient.makebucket("spacedata"); } // 使用putobject上传一个文件到存储桶中。 // minioclient.putobject("spacedata", "测试.jpg", "c:\\users\\sundasheng44\\desktop\\1.png"); // minioclient.removeobject("spacedata", "20200916/8ca27855ba884d7da1496fb96907a759.dwg"); iterable<result<item>> list = minioclient.listobjects("spacedata", "compileresult/"); list<string> list1 = lists.newarraylist(); list.foreach(e -> { try { list1.add("1"); string url = minioclient.getobjecturl("spacedata", e.get().objectname()); system.out.println(url); //getfile(url, "c:\\users\\liuya\\desktop\\" + e.get().objectname()); system.out.println(e.get().objectname()); // minioclient.removeobject("spacedata", e.get().objectname()); } catch (invalidbucketnameexception invalidbucketnameexception) { invalidbucketnameexception.printstacktrace(); } catch (nosuchalgorithmexception nosuchalgorithmexception) { nosuchalgorithmexception.printstacktrace(); } catch (insufficientdataexception insufficientdataexception) { insufficientdataexception.printstacktrace(); } catch (ioexception ioexception) { ioexception.printstacktrace(); } catch (invalidkeyexception invalidkeyexception) { invalidkeyexception.printstacktrace(); } catch (noresponseexception noresponseexception) { noresponseexception.printstacktrace(); } catch (xmlpullparserexception xmlpullparserexception) { xmlpullparserexception.printstacktrace(); } catch (errorresponseexception errorresponseexception) { errorresponseexception.printstacktrace(); } catch (internalexception internalexception) { internalexception.printstacktrace(); } }); system.out.println(list1.size()); } catch (minioexception e) { system.out.println("error occurred: " + e); } } /** * 文件流下载(原始文件名) * * @author sunboqiang * @date 2020/10/22 */ public responseentity<byte[]> filedownload(string url, string filename, httpservletrequest request) { return this.downloadmethod(url, filename, request); } private file getfile(string url, string filename) { inputstream in = null; // 创建文件 string dirpath = filename.substring(0, filename.lastindexof("/")); file dir = new file(dirpath); if (!dir.exists()) { dir.mkdirs(); } file file = new file(filename); try { url url1 = new url(url); in = url1.openstream(); // 输入流转换为字节流 byte[] buffer = filecopyutils.copytobytearray(in); // 字节流写入文件 filecopyutils.copy(buffer, file); // 关闭输入流 in.close(); } catch (ioexception e) { log.error("文件获取失败:" + e); return null; } finally { try { in.close(); } catch (ioexception e) { log.error("", e); } } return file; } public responseentity<byte[]> downloadmethod(string url, string filename, httpservletrequest request) { httpheaders heads = new httpheaders(); heads.add(httpheaders.content_type, "application/octet-stream; charset=utf-8"); try { if (request.getheader("user-agent").tolowercase().indexof("firefox") > 0) { // firefox浏览器 filename = new string(filename.getbytes(standardcharsets.utf_8), "iso8859-1"); } else if (request.getheader("user-agent").touppercase().indexof("msie") > 0) { // ie浏览器 filename = urlencoder.encode(filename, "utf-8"); } else if (request.getheader("user-agent").touppercase().indexof("edge") > 0) { // win10浏览器 filename = urlencoder.encode(filename, "utf-8"); } else if (request.getheader("user-agent").touppercase().indexof("chrome") > 0) { // 谷歌 filename = new string(filename.getbytes(standardcharsets.utf_8), "iso8859-1"); } else { //万能乱码问题解决 filename = new string(filename.getbytes(standardcharsets.utf_8), standardcharsets.iso_8859_1); } } catch (unsupportedencodingexception e) { // log.error("", e); } heads.add(httpheaders.content_disposition, "attachment;filename=" + filename); try { //inputstream in = new fileinputstream(file); url url1 = new url(url); inputstream in = url1.openstream(); // 输入流转换为字节流 byte[] buffer = filecopyutils.copytobytearray(in); responseentity<byte[]> responseentity = new responseentity<>(buffer, heads, httpstatus.ok); //file.delete(); return responseentity; } catch (exception e) { log.error("", e); } return null; }
创建 filesminioservice 服务类
import com.baomidou.mybatisplus.core.conditions.query.querywrapper;import com.baomidou.mybatisplus.extension.service.impl.serviceimpl;import com.gis.spacedata.common.constant.response.responsecodeconst;import com.gis.spacedata.common.domain.responsedto;import com.gis.spacedata.domain.dto.file.vo.uploadvo;import com.gis.spacedata.domain.dto.minio.minioitem;import com.gis.spacedata.domain.entity.file.fileentity;import com.gis.spacedata.enums.file.fileservicetypeenum;import com.gis.spacedata.handler.smartbusinessexception;import com.gis.spacedata.mapper.file.filedao;import lombok.extern.slf4j.slf4j;import org.apache.commons.codec.digest.digestutils;import org.apache.commons.lang3.stringutils;import org.springblade.core.tool.utils.fileutil;import org.springframework.beans.factory.annotation.autowired;import org.springframework.beans.factory.annotation.value;import org.springframework.http.responseentity;import org.springframework.scheduling.concurrent.threadpooltaskexecutor;import org.springframework.stereotype.service;import org.springframework.web.multipart.multipartfile; import javax.annotation.resource;import javax.servlet.http.httpservletrequest;import java.io.file;import java.io.ioexception;import java.io.inputstream;import java.time.localdatetime;import java.time.format.datetimeformatter;import java.util.list;import java.util.uuid; @service@slf4jpublic class filesminioservice extends serviceimpl<filedao, fileentity> { @autowired private miniotemplate miniotemplate; @resource private threadpooltaskexecutor taskexecutor; /** * 图片大小限制 **/ @value("#{${minio.imgsize}}") private long imgsize; /** * 文件大小限制 **/ @value("#{${minio.filesize}}") private long filesize; @value("${minio.bucket}") private string bucket; /** * 下载地址 **/ @value("${minio.http-url}") private string httpurl; /** * 判断是否图片 */ private boolean isimage(string filename) { //设置允许上传文件类型 string suffixlist = "jpg,gif,png,ico,bmp,jpeg"; // 获取文件后缀 string suffix = filename.substring(filename.lastindexof(".") + 1); return suffixlist.contains(suffix.trim().tolowercase()); } /** * 验证文件大小 * * @param upfile * @param filename 文件名称 * @throws exception */ private void filecheck(multipartfile upfile, string filename) throws exception { long size = upfile.getsize(); if (isimage(filename)) { if (size > imgsize) { throw new exception("上传对图片大于:" + (imgsize / 1024 / 1024) + "m限制"); } } else { if (size > filesize) { throw new exception("上传对文件大于:" + (filesize / 1024 / 1024) + "m限制"); } } } /** * 文件上传 * * @author sunboqiang * @date 2020/9/9 */ public responsedto<uploadvo> fileupload(multipartfile upfile) throws ioexception { string originalfilename = upfile.getoriginalfilename(); try { filecheck(upfile, originalfilename); } catch (exception e) { return responsedto.wrap(responsecodeconst.error, e.getmessage()); } if (stringutils.isblank(originalfilename)) { return responsedto.wrap(responsecodeconst.error_param, "文件名称不能为空"); } uploadvo vo = new uploadvo(); string url; //获取文件md5,查找数据库,如果有,则不需要上传了 string md5 = digestutils.md5hex(upfile.getinputstream()); querywrapper<fileentity> query = new querywrapper<>(); query.lambda().eq(fileentity::getmd5, md5); query.lambda().eq(fileentity::getstoragetype, fileservicetypeenum.minio_oss.getlocationtype()); fileentity fileentity = basemapper.selectone(query); if (null != fileentity) { //url = miniotemplate.getobjecturl(bucket,fileentity.getfilename()); vo.setid(fileentity.getid()); vo.setfilename(originalfilename); vo.seturl(httpurl + fileentity.getfileurl()); vo.setnewfilename(fileentity.getfilename()); vo.setfilesize(upfile.getsize()); vo.setfilelocationtype(fileservicetypeenum.minio_oss.getlocationtype()); log.info("文件已上传,直接获取"); return responsedto.succdata(vo); } //拼接文件名 string filename = generatefilename(originalfilename); try { // 检查存储桶是否已经存在 boolean isexist = miniotemplate.bucketexists(bucket); if (isexist) { log.info("bucket already exists."); } else { // 创建一个名为asiatrip的存储桶,用于存储照片的zip文件。 miniotemplate.createbucket(bucket); } // 使用putobject上传一个文件到存储桶中。 miniotemplate.putobject(bucket, filename, upfile.getinputstream()); log.info("上传成功."); //生成一个外部链接 //url = miniotemplate.getobjecturl(bucket,filename); //已经设置永久链接,直接获取 url = httpurl + bucket + "/" + filename; fileentity = new fileentity(); fileentity.setstoragetype(fileservicetypeenum.minio_oss.getlocationtype()); fileentity.setfilename(filename); fileentity.setoriginalfilename(originalfilename); fileentity.setfileurl(bucket + "/" + filename); fileentity.setfilesize(upfile.getsize()); fileentity.setmd5(md5); basemapper.insert(fileentity); } catch (exception e) { return responsedto.wrap(responsecodeconst.error, "上传失败!"); } vo.setfilename(originalfilename); vo.setid(fileentity.getid()); vo.seturl(url); vo.setnewfilename(filename); vo.setfilesize(upfile.getsize()); vo.setfilelocationtype(fileservicetypeenum.minio_oss.getlocationtype()); return responsedto.succdata(vo); } /** * 生成文件名字 * 当前年月日时分秒 +32位 uuid + 文件格式后缀 * * @param originalfilename * @return string */ private string generatefilename(string originalfilename) { string time = localdatetime.now().format(datetimeformatter.ofpattern("yyyymmdd")); string uuid = uuid.randomuuid().tostring().replaceall("-", ""); string filetype = originalfilename.substring(originalfilename.lastindexof(".")); return time + "/" + uuid + filetype; } /** * 文件上传(不做重复校验) * * @author sunboqiang * @date 2020/9/25 */ public responsedto<uploadvo> fileuploadrep(multipartfile upfile) throws ioexception { string originalfilename = upfile.getoriginalfilename(); try { filecheck(upfile, originalfilename); } catch (exception e) { return responsedto.wrap(responsecodeconst.error, e.getmessage()); } if (stringutils.isblank(originalfilename)) { return responsedto.wrap(responsecodeconst.error_param, "文件名称不能为空"); } uploadvo vo = new uploadvo(); string url; //获取文件md5 fileentity fileentity = new fileentity(); //拼接文件名 string filename = generatefilename(originalfilename); try { // 检查存储桶是否已经存在 boolean isexist = miniotemplate.bucketexists(bucket); if (isexist) { log.info("bucket already exists."); } else { // 创建一个名为asiatrip的存储桶,用于存储照片的zip文件。 miniotemplate.createbucket(bucket); } // 使用putobject上传一个文件到存储桶中。 miniotemplate.putobject(bucket, filename, upfile.getinputstream()); log.info("上传成功."); //生成一个外部链接 //url = miniotemplate.getobjecturl(bucket,filename); //已经设置永久链接,直接获取 url = httpurl + bucket + "/" + filename; fileentity.setstoragetype(fileservicetypeenum.minio_oss.getlocationtype()); fileentity.setfilename(filename); fileentity.setoriginalfilename(originalfilename); fileentity.setfileurl(bucket + "/" + filename); fileentity.setfilesize(upfile.getsize()); basemapper.insert(fileentity); } catch (exception e) { return responsedto.wrap(responsecodeconst.error, "上传失败!"); } vo.setfilename(originalfilename); vo.setid(fileentity.getid()); vo.seturl(url); vo.setnewfilename(filename); vo.setfilesize(upfile.getsize()); vo.setfilelocationtype(fileservicetypeenum.minio_oss.getlocationtype()); return responsedto.succdata(vo); } /** * 文件流上传(不存数据库) * * @author sunboqiang * @date 2020/9/25 */ public responsedto<uploadvo> uploadstream(inputstream inputstream, string originalfilename) { uploadvo vo = new uploadvo(); string url; //文件名 string filename = originalfilename; try { // 检查存储桶是否已经存在 boolean isexist = miniotemplate.bucketexists(bucket); if (isexist) { log.info("bucket already exists."); } else { // 创建一个名为asiatrip的存储桶,用于存储照片的zip文件。 miniotemplate.createbucket(bucket); } // 使用putobject上传一个文件到存储桶中。 miniotemplate.putobject(bucket, filename, inputstream); log.info("上传成功."); //生成一个外部链接 //url = miniotemplate.getobjecturl(bucket,filename); //已经设置永久链接,直接获取 url = httpurl + bucket + "/" + filename; } catch (exception e) { return responsedto.wrap(responsecodeconst.error, "上传失败!"); } vo.setfilename(originalfilename); vo.seturl(url); vo.setnewfilename(filename); vo.setfilelocationtype(fileservicetypeenum.minio_oss.getlocationtype()); return responsedto.succdata(vo); } private string generatefilenametwo(string originalfilename) { string time = localdatetime.now().format(datetimeformatter.ofpattern("yyyymmdd")); return time + "/" + originalfilename; } /** * 文件查询 * * @author sunboqiang * @date 2020/9/25 */ public responsedto<uploadvo> findfilebyid(long id) { fileentity fileentity = basemapper.selectbyid(id); if (null == fileentity) { return responsedto.wrap(responsecodeconst.error_param, "文件不存在"); } uploadvo vo = new uploadvo(); /*string url = miniotemplate.getobjecturl(bucket,fileentity.getfilename()); if(stringutils.isempty(url)){ return responsedto.wrap(responsecodeconst.error_param,"获取minio 文件url失败!"); }*/ vo.setfilename(fileentity.getoriginalfilename()); vo.seturl(httpurl + fileentity.getfileurl()); vo.setnewfilename(fileentity.getfilename()); vo.setfilesize(fileentity.getfilesize()); vo.setfilelocationtype(fileservicetypeenum.minio_oss.getlocationtype()); return responsedto.succdata(vo); } /** * 文件流式下载 * * @author sunboqiang * @date 2020/10/22 */ public responseentity<byte[]> downloadfile(long id, httpservletrequest request) { fileentity fileentity = basemapper.selectbyid(id); if (null == fileentity) { throw new smartbusinessexception("文件信息不存在"); } if (stringutils.isempty(fileentity.getfileurl())) { throw new smartbusinessexception("文件url为空"); } responseentity<byte[]> stream = miniotemplate.filedownload(httpurl + fileentity.getfileurl(), fileentity.getoriginalfilename(), request); return stream; } /** * 文件删除(通过文件名) * * @author tarzan liu * @date 2020/11/11 */ public responsedto<string> deletefiles(list<string> filenames) { try { for (string filename : filenames) { miniotemplate.removeobject(bucket, filename); } } catch (exception e) { return responsedto.wrap(responsecodeconst.error, e.getmessage()); } return responsedto.succ(); } /** * tarzan liu * * @author tarzan liu * @date 2020/11/11 */ public responsedto<string> downloadtargetdir(string objectname, string dirpath) { miniotemplate.downloadtargetdir(bucket, objectname, dirpath); return responsedto.succ(); } /** * 下载备份编译结果 * * @param dirpath * @return {@link boolean} * @author zhangpeng * @date 2021年10月15日 */ public boolean downloadcompile(string dirpath) { if (!miniotemplate.bucketexists(bucket)) { log.info("bucket not exists."); return true; } list<minioitem> list = miniotemplate.getallobjectsbyprefix(bucket, "compileresult/", true); list.foreach(e -> { string url = miniotemplate.getobjecturl(bucket, e.getobjectname()); inputstream miniostream = miniotemplate.getobject(bucket, e.getobjectname()); file file = new file(dirpath + url.substring(url.indexof("compileresult")-1)); if (!file.getparentfile().exists()) { file.getparentfile().mkdirs(); } fileutil.tofile(miniostream, file); }); log.info("downloadcompile complete."); return true; }
部分操作数据库的相关代码省略,不再展示
创建filesminiocontroller 服务接口
import com.alibaba.fastjson.jsonobject;import com.alibaba.fastjson.serializer.serializerfeature;import com.gis.spacedata.common.anno.noneedlogin;import com.gis.spacedata.common.domain.responsedto;import com.gis.spacedata.domain.dto.file.vo.uploadvo;import com.gis.spacedata.service.file.filesminioservice;import io.swagger.annotations.api;import io.swagger.annotations.apioperation;import org.springframework.beans.factory.annotation.autowired;import org.springframework.http.responseentity;import org.springframework.web.bind.annotation.*;import org.springframework.web.multipart.multipartfile; import javax.servlet.http.httpservletrequest;import java.io.bytearrayinputstream;import java.io.ioexception;import java.io.inputstream;import java.util.arrays;import java.util.list; @api(tags = {"minio文件服务"})@restcontrollerpublic class filesminiocontroller { @autowired private filesminioservice filesminioservice; @apioperation(value = "文件上传(md5去重上传) by sunboqiang") @postmapping("/minio/uploadfile/md5") @noneedlogin public responsedto<uploadvo> uploadfile(multipartfile file) throws ioexception { return filesminioservice.fileupload(file); } @apioperation(value = "文件上传(不做重复校验) by sunboqiang") @postmapping("/minio/uploadfile/norepeatcheck") public responsedto<uploadvo> fileuploadrep(multipartfile file) throws ioexception { return filesminioservice.fileuploadrep(file); } @apioperation(value = "文件流上传 by sunboqiang") @postmapping("/minio/uploadfile/stream/{filename}") public responsedto<uploadvo> uploadstream(inputstream inputstream, @pathvariable("filename") string filename) throws ioexception { return filesminioservice.uploadstream(inputstream, filename); } @apioperation(value = "文件查询(永久链接) by sunboqiang") @getmapping("/minio/getfileurl/{id}") public responsedto<uploadvo> findfilebyid(@pathvariable("id") long id) { return filesminioservice.findfilebyid(id); } @apioperation(value = "文件流式下载 by sunboqiang") @getmapping("/minio/downloadfile/stream") public responseentity<byte[]> downloadfile(@requestparam long id, httpservletrequest request) { return filesminioservice.downloadfile(id, request); } @apioperation(value = "文件删除(通过文件名) by sunboqiang") @postmapping("/minio/deletefiles") public responsedto<string> deletefiles(@requestbody list<string> filenames) { return filesminioservice.deletefiles(filenames); }}
以上就是springboot怎么整合minio实现文件服务的详细内容。
