springboot 读取文件夹返回树给前端
时间: 2023-11-09 14:08:11 浏览: 81
可以使用递归的方式遍历文件夹,并将文件夹及其子文件夹信息封装成树形结构返回给前端。以下是一个示例代码:
```java
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
@Controller
public class FileController {
@GetMapping("/tree")
@ResponseBody
public List<TreeNode> getFileTree() {
String rootPath = "D:/files"; // 文件夹根路径
File rootFile = new File(rootPath);
if (!rootFile.exists() || !rootFile.isDirectory()) {
return null;
}
TreeNode root = new TreeNode(rootFile.getName(), true);
buildFileTree(root, rootFile);
List<TreeNode> treeNodes = new ArrayList<>();
treeNodes.add(root);
return treeNodes;
}
private void buildFileTree(TreeNode parent, File parentFile) {
File[] files = parentFile.listFiles();
if (files != null && files.length > 0) {
for (File file : files) {
if (file.isDirectory()) {
TreeNode treeNode = new TreeNode(file.getName(), true);
parent.addChild(treeNode);
buildFileTree(treeNode, file);
} else {
TreeNode treeNode = new TreeNode(file.getName(), false);
parent.addChild(treeNode);
}
}
}
}
private static class TreeNode {
private String name;
private boolean directory;
private List<TreeNode> children;
public TreeNode(String name, boolean directory) {
this.name = name;
this.directory = directory;
}
public String getName() {
return name;
}
public boolean isDirectory() {
return directory;
}
public List<TreeNode> getChildren() {
return children;
}
public void addChild(TreeNode child) {
if (children == null) {
children = new ArrayList<>();
}
children.add(child);
}
}
}
```
通过访问 `/tree` 接口,可以获取文件夹树形结构的数据,前端可以根据这些数据进行展示。
阅读全文