首頁  >  文章  >  Java  >  java怎麼實作資料夾上傳功能

java怎麼實作資料夾上傳功能

PHPz
PHPz轉載
2023-05-10 20:52:042681瀏覽

一、前端如何設定上傳元件並將資源上傳到後台服務

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(&#39;&#39;);
      })
}

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中文網其他相關文章!

陳述:
本文轉載於:yisu.com。如有侵權,請聯絡admin@php.cn刪除