文件上传基本都用过,是用的MultipartFile;
文件夹上传用的类,差不多:MultipartFile[]、
工具类:
FolderUtils.java
package com.mods.utils;
import java.io.File;
import java.io.IOException;
import org.springframework.web.multipart.MultipartFile;
public class FolderUtils {
/**
* 在basePath下保存上传的文件夹
*
* @param basePath 上传后保存的路径(例如C:/)
* @param files 文件夹
*/
public static void saveMultiFile(String basePath, MultipartFile[] files) throws Exception {
if (files == null || files.length == 0) {
return;
}
if (basePath.endsWith("/") || basePath.endsWith("\\")) {
basePath = basePath.substring(0, basePath.length() - 1);
}
for (MultipartFile file : files) {
String filePath = basePath + "/" + file.getOriginalFilename();
makeDir(filePath);
File dest = new File(filePath);
file.transferTo(dest);
}
}
/**
* 确保目录存在,不存在则创建
*
* @param filePath
*/
private static void makeDir(String filePath) {
if (filePath.lastIndexOf('/') > 0) {
String dirPath = filePath.substring(0, filePath.lastIndexOf('/'));
File dir = new File(dirPath);
if (!dir.exists()) {
dir.mkdirs();
}
}
}
}
Controller中的方法
@ApiOperation("上传文件夹-返回文件夹路径")
@PostMapping("/upload_folder")
public String uploadFolder(MultipartFile[] folder) {
String basePath = filePathProperties.getPubPath() + System.currentTimeMillis() + File.separator;
try {
FolderUtils.saveMultiFile(basePath, folder);
} catch (Exception e) {
return "error";
}
String returnPath = basePath.replace("\\", "/");
// if (returnPath.startsWith("D:/")) { //根据个人需要,把返回的字符串前的盘符删掉
// return returnPath.substring(3);
// }
return returnPath;
}
最后可以写一个前端页面用于测试
放在Resource下的static文件夹下,访问方式:端口号后跟 folder.html
folder.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>文件夹上传</title>
</head>
<body>
<form action="/common/upload_folder" method="post" enctype="multipart/form-data">
<!-- html5支持选择文件夹上传 -->
<input type="file" name="folder" multiple webkitdirectory>
<button type="submit">上传</button>
</form>
</body>
</html>