概述
本文仅作为快速入门,深入学习及使用详见官网
云存储
在开发过程当中,会使用到存文档、图片、视频、音频等等,这些都会涉及存储的问题,文件可以直接存服务器,但需要考虑带宽和存储空间,另外一种方式就是使用云存储。目前主流的云存储有阿里云oss、华为云obs、七牛云kodo、腾讯云cos、百度云 bos、又拍云uss、minio 等。
x spring file storage 介绍
在 springboot 中通过简单的方式将文件存储到 本地、ftp、sftp、webdav、谷歌云存储、阿里云oss、华为云obs、七牛云kodo、腾讯云cos、百度云 bos、又拍云uss、minio、 aws s3、金山云 ks3、美团云 mss、京东云 oss、天翼云 oos、移动云 eos、沃云 oss、 网易数帆 nos、ucloud us3、青云 qingstor、平安云 obs、首云 oss、ibm cos、其它兼容 s3 协议的平台。
支持的平台如下图:
快速入门
添加依赖
<dependencies> <!-- spring-file-storage 必须要引入 --> <dependency> <groupid>cn.xuyanwu</groupid> <artifactid>spring-file-storage</artifactid> <version>2.1.0</version> </dependency> <!-- 华为云obs 不使用的情况下可以不引入 --> <dependency> <groupid>com.huaweicloud</groupid> <artifactid>esdk-obs-java</artifactid> <version>3.22.12</version> </dependency> <!-- 阿里云oss 不使用的情况下可以不引入 --> <dependency> <groupid>com.aliyun.oss</groupid> <artifactid>aliyun-sdk-oss</artifactid> <version>3.16.1</version> </dependency>
添加配置文件
注:以下配置是 2.1.0 版本的配置
dromara: x-file-storage: #文件存储配置 default-platform: huawei-obs-1 #默认使用的存储平台 thumbnail-suffix: ".min.jpg" #缩略图后缀,例如【.min.jpg】【.png】 # 对应平台的配置写在这里,注意缩进要对齐 huawei-obs: - platform: huawei-obs-1 # 存储平台标识 enable-storage: true # 启用存储。只有状态开启才会被识别到 access-key: ?? secret-key: ?? end-point: ?? bucket-name: ?? domain: ?? # 访问域名,注意“/”结尾,例如:http://abc.obs.com/ base-path: test/ # 基础路径 # 本地存储(升级版) local-plus: - platform: local-plus-1 # 存储平台标识 enable-storage: true #启用存储 enable-access: true #启用访问(线上请使用 nginx 配置,效率更高) domain: http://127.0.0.1:8080/file/ # 访问域名,例如:“http://127.0.0.1:8030/file/”,注意后面要和 path-patterns 保持一致,“/”结尾,本地存储建议使用相对路径,方便后期更换域名 base-path: local-plus/ # 基础路径 path-patterns: /file/** # 访问路径 storage-path: d:/temp/ # 存储路径
编码
显式的开启文件上传功能
在启动类上加上@enablefilestorage
注解
@enablefilestorage @springbootapplication public class springfilestoragetestapplication { public static void main(string[] args) { springapplication.run(springfilestoragetestapplication.class,args); } }
上传
支持 file、multipartfile、byte[]、inputstream、url、uri、string、httpservletrequest,大文件会自动分片上传。
@restcontroller public class filedetailcontroller { @autowired private filestorageservice filestorageservice;//注入实列 /** * 上传文件 */ @postmapping("/upload") public fileinfo upload(multipartfile file) { return filestorageservice.of(file).upload(); } /** * 上传文件,成功返回文件 url */ @postmapping("/upload2") public string upload2(multipartfile file) { fileinfo fileinfo = filestorageservice.of(file) .setpath("upload/") //保存到相对路径下,为了方便管理,不需要可以不写 .setobjectid("0") //关联对象id,为了方便管理,不需要可以不写 .setobjecttype("0") //关联对象类型,为了方便管理,不需要可以不写 .putattr("role","admin") //保存一些属性,可以在切面、保存上传记录、自定义存储平台等地方获取使用,不需要可以不写 .upload(); //将文件上传到对应地方 return fileinfo == null ? "上传失败!" : fileinfo.geturl(); } /** * 上传图片,成功返回文件信息 * 图片处理使用的是 https://github.com/coobird/thumbnailator */ @postmapping("/upload-image") public fileinfo uploadimage(multipartfile file) { return filestorageservice.of(file) .image(img -> img.size(1000,1000)) //将图片大小调整到 1000*1000 .thumbnail(th -> th.size(200,200)) //再生成一张 200*200 的缩略图 .upload(); } /** * 上传文件到指定存储平台,成功返回文件信息 */ @postmapping("/upload-platform") public fileinfo uploadplatform(multipartfile file) { return filestorageservice.of(file) .setplatform("aliyun-oss-1") //使用指定的存储平台 .upload(); } /** * 直接读取 httpservletrequest 中的文件进行上传,成功返回文件信息 * 使用这种方式有些注意事项,请查看文档 基础功能-上传 章节 */ @postmapping("/upload-request") public fileinfo uploadplatform(httpservletrequest request) { return filestorageservice.of(request).upload(); } }
文件是否存在、下载、删除
//手动构造文件信息,可用于其它操作 fileinfo fileinfo = new fileinfo() .setplatform("huawei-obs-1") .setbasepath("test/") .setpath("aa/") .setfilename("image.png") .setthfilename("image.png.min.jpg"); //文件是否存在 boolean exists = filestorageservice.exists(fileinfo); //下载 byte[] bytes = filestorageservice.download(fileinfo).bytes(); // 下载到文件 filestorageservice.download(fileinfo).file("c:\\a.jpg"); // 下载缩略图 filestorageservice.downloadth(fileinfo).file("c:\\th.jpg"); //删除 filestorageservice.delete(fileinfo); // 如果将文件记录保存到数据库中,还可以更方便的根据 url 进行操作 //直接从数据库中获取 fileinfo 对象,更加方便执行其它操作 fileinfo fileinfo = filestorageservice.getfileinfobyurl("https://abc.def.com/test/aa/image.png"); //文件是否存在 boolean exists = filestorageservice.exists("https://abc.def.com/test/aa/image.png"); //下载 byte[] bytes = filestorageservice.download("https://abc.def.com/test/aa/image.png").bytes(); //删除 filestorageservice.delete("https://abc.def.com/test/aa/image.png");
监听器
// 下载文件 显示进度 filestorageservice.download(fileinfo).setprogressmonitor(new progresslistener() { @override public void start() { system.out.println("下载开始"); } @override public void progress(long progresssize,long allsize) { system.out.println("已下载 " + progresssize + " 总大小" + allsize); } @override public void finish() { system.out.println("下载结束"); } }).file("c:\\a.jpg");
切面
工具还提供了每种操作的切面,可以在每个动作的前后进行干预,比如打日志,实现 filestorageaspect
类重写对应动作的 xxxaround 方法。
/** * 使用切面打印文件上传和删除的日志 */ @slf4j @component public class logfilestorageaspect implements filestorageaspect { /** * 上传,成功返回文件信息,失败返回 null */ @override public fileinfo uploadaround(uploadaspectchain chain, fileinfo fileinfo, uploadpretreatment pre, filestorage filestorage, filerecorder filerecorder) { log.info("上传文件 before -> {}",fileinfo); fileinfo = chain.next(fileinfo,pre,filestorage,filerecorder); log.info("上传文件 after -> {}",fileinfo); return fileinfo; } }
表设计
-- mysql drop table if exists `file_detail`; create table `file_detail` ( `id` int(10) unsigned not null auto_increment comment '文件id', `url` varchar(256) character set utf8 collate utf8_general_ci not null comment '文件访问地址', `size` bigint(20) null default null comment '文件大小,单位字节', `filename` varchar(256) character set utf8 collate utf8_general_ci null default null comment '文件名称', `original_filename` varchar(256) character set utf8 collate utf8_general_ci null default null comment '原始文件名', `base_path` varchar(256) character set utf8 collate utf8_general_ci null default null comment '基础存储路径', `path` varchar(256) character set utf8 collate utf8_general_ci null default null comment '存储路径', `ext` varchar(32) character set utf8 collate utf8_general_ci null default null comment '文件扩展名', `content_type` varchar(32) character set utf8 collate utf8_general_ci null default null comment 'mime类型', `platform` varchar(32) character set utf8 collate utf8_general_ci null default null comment '存储平台', `th_url` varchar(256) character set utf8 collate utf8_general_ci null default null comment '缩略图访问路径', `th_filename` varchar(256) character set utf8 collate utf8_general_ci null default null comment '缩略图名称', `th_size` bigint(20) null default null comment '缩略图大小,单位字节', `th_content_type` varchar(32) character set utf8 collate utf8_general_ci null default null comment '缩略图mime类型', `object_id` varchar(32) character set utf8 collate utf8_general_ci null default null comment '文件所属对象id', `object_type` varchar(32) character set utf8 collate utf8_general_ci null default null comment '文件所属对象类型,例如用户头像,评价图片', `attr` text character set utf8 collate utf8_general_ci null default null comment '附加属性', `create_time` datetime(0) null default null comment '创建时间', primary key (`id`) using btree ) engine = innodb auto_increment = 1 character set = utf8 collate = utf8_general_ci comment = '文件记录表' row_format = dynamic; -- postgre 自定义 create table if not exists "file_detail" ( id varchar(255) not null, url varchar(255) not null, "size" bigint null, filename varchar(255) null, original_filename varchar(255) null, base_path varchar(255) null, "path" varchar(255) null, ext varchar(255) null, content_type varchar(255) null, platform varchar(255) null, th_url varchar(255) null, th_filename varchar(255) null, th_size bigint null, th_content_type varchar(255) null, object_id varchar(255) null, object_type varchar(255) null, attr varchar(255) null, create_time timestamp null, project_id uuid null, tenant_id uuid null, primary key ("id") ); -- column comments comment on table file_detail is '文件记录表'; comment on column public.file_detail.id is '主键'; comment on column public.file_detail.url is '文件访问地址'; comment on column public.file_detail."size" is '文件大小,单位字节'; comment on column public.file_detail.filename is '文件名称'; comment on column public.file_detail.original_filename is '原始文件名'; comment on column public.file_detail.base_path is '基础存储路径'; comment on column public.file_detail."path" is '存储路径'; comment on column public.file_detail.ext is '文件扩展名'; comment on column public.file_detail.content_type is 'mime类型'; comment on column public.file_detail.platform is '存储平台'; comment on column public.file_detail.th_url is '缩略图访问路径'; comment on column public.file_detail.th_filename is '缩略图名称'; comment on column public.file_detail.th_size is '缩略图大小,单位字节'; comment on column public.file_detail.th_content_type is '缩略图mime类型'; comment on column public.file_detail.object_id is '文件所属对象id'; comment on column public.file_detail.object_type is '文件所属对象类型,例如用户头像,评价图'; comment on column public.file_detail.attr is '附加属性'; comment on column public.file_detail.create_time is '创建时间'; comment on column public.file_detail.project_id is '项目id'; comment on column public.file_detail.tenant_id is '租户id';
参考资料
到此这篇关于spring file storage(文件的对象存储)框架基本使用指南的文章就介绍到这了,更多相关spring file storage内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论