首頁 > Java > java教程 > 主體

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

PHPz
發布: 2023-05-10 20:52:04
轉載
2696 人瀏覽過

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

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
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!