java怎么实现文件夹上传功能

PHPz
PHPz 转载
2023-05-10 20:52:04 1683浏览

一、前端如何设置上传组件并将资源上传到后台服务

1)首先我们需要新建一个用来提交文件夹的form表单

1.添加一个 type=file 的 input 提交组件,添加 webkitdirectory 标识来使用文件夹上传功能

2.添加 @change=“uploadSoundCodeFolder” 事件,当我们上传了文件夹后将触发 uploadSoundCodeFolder() 函数来处理上传逻辑

<form id="uploadSoundCodeFolderForm" 
 method="post" 
enctype="multipart/form-data">
  <input id="fileFolder" name="fileFolder" type="file" 
 		@change="uploadSoundCodeFolder" webkitdirectory>
</form>

uploadSoundCodeFolder() 实现逻辑如下

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

<!-- 首先创建一个按钮用来触发上传事件 uploadSoundCodeBtn() -->
<el-button  v-loading="uploadSoundCodeLoading" 
@click="uploadSoundCodeBtn">
上传文件夹
</el-button>
/*上传事件触发的方法*/
uploadSoundCodeBtn(){
  $("#fileFolder").click();
},

二、后台如何接收处理文件夹表单数据

这里我们使用 List fileFolde 类型来接受前端发来的文件集合,fileFolde为表单里面的 name

@RequestMapping(value="/uploadSoundCode",method= RequestMethod.POST)
public AjaxResult uploadSoundCode(List<MultipartFile> fileFolde) throws IOException {
        String soundCodeUrl = HereUtil.uploadSoundCode(fileFolder);
        return AjaxResult.success(soundCodeUrl);
    }

然后根据业务将文件保存到服务器就行了

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怎么实现文件夹上传功能的详细内容,更多请关注php中文网其它相关文章!

声明:本文转载于:亿速云,如有侵犯,请联系admin@php.cn删除