WEB端实现文件夹上传
webkitdirectory属性。这个属性加上之后,就是选择文件夹,然后根据自己业务上传至后台;
前端代码:
<form action="${ctxPath}/invoice/uploadFolder" method="post" enctype="multipart/form-data">
<input name="chooseFolder" type="file" id="chooseFolder" webkitdirectory/>
<input type="submit" id="uploadFolder" style="display : none"/>
</form>
<iframe name="form" id="form" style="display:none"></iframe>
监听上传,ajax提交请求:
/* 监听上传文件夹按钮 */
$("#chooseFolder").on("change", function() {
var sIndex = layer.msg("识别数据中,请稍候", {icon:16, time:false, shade:0.1});
dataList = [];
var fileList = [];
var files = this.files;
console.log(files);
for(var i = 0;i<files.length;i++){
fileList.push(files[i])
}
let formData = new FormData()
formData.append("chooseFolder",files);
fileList.forEach(function (file) {
formData.append('chooseFolder',file, file.name)
})
$.ajax({
url: "${ctxPath}/invoice/uploadFolder",
data: formData,
type: "Post",
dataType: "formData",
cache: false,//上传文件无需缓存
processData: false,//用于对data参数进行序列化处理 这里必须false
contentType: false, //必须
complete: function(result) {
var responseText = result.responseText
var data = JSON.parse(responseText)
data.data.forEach(function (d){
dataList.push(d);
})
tableInfo.reload({
data: dataList,
limit: dataList.length,
});
layer.close(sIndex);
}
})
});
后端Controller:
@RequestMapping("uploadFolder")
public String uploadFolder(@RequestParam("chooseFolder") MultipartFile[] chooseFolder, HttpServletRequest request) throws IOException {
for(MultipartFile myFile: chooseFolder){
if(myFile.isEmpty()){
System.out.println("空");
}else {
System.out.println("文件长度" + myFile.getSize());
System.out.println("文件类型" + myFile.getContentType());
System.out.println("文件名" + myFile.getName());
System.out.println("文件原名" + myFile.getOriginalFilename());
System.out.println("*********************************");
// 写处理图片业务
}
}
}
参考文章:http://blog.ncmem.com/wordpress/2023/11/06/web%e7%ab%af%e5%ae%9e%e7%8e%b0%e6%96%87%e4%bb%b6%e5%a4%b9%e4%b8%8a%e4%bc%a0/
欢迎入群一起讨论