前言
有时我们后台管理等服务可能会有这样一个简单需求,就是根据文件夹将整个文件夹下的所有资源都上传到我们的服务器上,本人也是搜索了大量资料,最终以最简单便捷的方式实现该功能,具体操作步骤如下
一、前端如何设置上传组件并将资源上传到后台服务
这里的项目框架为若依VUE版本,下面将核心的代码抽离出来进行代码示例,方便大家快速阅读
1)首先我们需要新建一个用来提交文件夹的form表单
1.添加一个 type=file 的 input 提交组件,添加 webkitdirectory 标识来使用文件夹上传功能
2.添加 @change=“uploadSoundCodeFolder” 事件,当我们上传了文件夹后将触发 uploadSoundCodeFolder() 函数来处理上传逻辑
1
2
3
4
5
6
|
< form id = "uploadSoundCodeFolderForm" style = "display: none" method = "post" enctype = "multipart/form-data" > < input id = "fileFolder" name = "fileFolder" type = "file" @ change = "uploadSoundCodeFolder" webkitdirectory> </ form > |
uploadSoundCodeFolder() 实现逻辑如下
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
uploadSoundCodeFolder(e){ this .uploadSoundCodeLoading = true ; //获取到选中的文件夹内的所有文件 //files 为一个集合 //可通过遍历 files 的方式获取到每个文件的大小等数据,来实现大小限制等需求 let files = e.target.files; //中间省略大小限制等需求...... //获取表单数据 let formData = new FormData(document.getElementById( "uploadSoundCodeFolderForm" )); //调用后台服务方法来提交该表单数据 uploadSoundCode(formData).then((res)=>{ _this.$message.success( "上传成功" ) //上传成功后清空表单数据 $( "#fileFolder" ).val( '' ); }) } |
2)然后我们添加自己框架内的一些按钮来触发该隐藏的表单
这样做的好处是使用了form文件夹上传的功能,却不用使用他的UI
1
2
3
4
5
|
<!-- 首先创建一个按钮用来触发上传事件 uploadSoundCodeBtn() --> < el-button v-loading = "uploadSoundCodeLoading" @ click = "uploadSoundCodeBtn" > 上传文件夹 </ el-button > |
1
2
3
4
|
/*上传事件触发的方法*/ uploadSoundCodeBtn(){ $( "#fileFolder" ).click(); }, |
二、后台如何接收处理文件夹表单数据
这里我们使用 List fileFolde 类型来接受前端发来的文件集合,fileFolde为表单里面的 name
1
2
3
4
5
|
@RequestMapping (value= "/uploadSoundCode" ,method= RequestMethod.POST) public AjaxResult uploadSoundCode(List<MultipartFile> fileFolde) throws IOException { String soundCodeUrl = HereUtil.uploadSoundCode(fileFolder); return AjaxResult.success(soundCodeUrl); } |
然后根据业务将文件保存到服务器就行了
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
public static String uploadSoundCode(List<MultipartFile> files) throws IOException { for (MultipartFile file : files) { String fileName = file.getOriginalFilename(); if (StrUtil.isBlank(fileName)){ continue ; } //上传后的URL全路径 String fullFilePath = "上传的跟路径" + fileName; FileUtil.writeFromStream(file.getInputStream(), fullFilePath); } return "" ; } |
总结
到此这篇关于java实现文件夹上传功能的文章就介绍到这了,更多相关springBoot实现文件夹上传内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!
原文链接:https://blog.csdn.net/sunhoms/article/details/128345126