1. Add a type= In the input submission component of file, add the webkitdirectory logo to use the folder upload function
2. Add the @change="uploadSoundCodeFolder" event. When we upload the folder, the uploadSoundCodeFolder() function will be triggered to handle the upload logic
<form id="uploadSoundCodeFolderForm" method="post" enctype="multipart/form-data"> <input id="fileFolder" name="fileFolder" type="file" @change="uploadSoundCodeFolder" webkitdirectory> </form>
uploadSoundCodeFolder() The implementation logic is as follows
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(''); }) }
The advantage of this is that we use form Folder upload function without using its UI
<!-- 首先创建一个按钮用来触发上传事件 uploadSoundCodeBtn() --> <el-button v-loading="uploadSoundCodeLoading" @click="uploadSoundCodeBtn"> 上传文件夹 </el-button>
/*上传事件触发的方法*/ uploadSoundCodeBtn(){ $("#fileFolder").click(); },
Here we use the List fileFolde type to accept the file collection sent by the front end. fileFolde is the name in the form
@RequestMapping(value="/uploadSoundCode",method= RequestMethod.POST) public AjaxResult uploadSoundCode(List<MultipartFile> fileFolde) throws IOException { String soundCodeUrl = HereUtil.uploadSoundCode(fileFolder); return AjaxResult.success(soundCodeUrl); }
Then just save the file to the server according to the business
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 ""; }
The above is the detailed content of How to implement folder upload function in java. For more information, please follow other related articles on the PHP Chinese website!