java 后端
主要使用两个api,File.listRoots()
和File.listFiles()
具体代码
public class FileController {
/**
* 获取文件树
* @return
*/
@GetMapping("/list")
public List<TreeData> list(String filePath){
List<TreeData> treeDataList = new ArrayList<>();
File[] pFiles;
if (filePath == null) {
pFiles = File.listRoots();
}else {
pFiles = new File(filePath).listFiles();
}
if (pFiles != null) {
for (File file : pFiles) {
String fileName = file.getName();
TreeData treeData = new TreeData(fileName);
if (StringUtils.isBlank(fileName)) {
treeData.setLabel(file.getPath());
}
if (file.isFile()) {
treeData.setLeaf(true);
}
treeData.setId(file.getPath());
treeDataList.add(treeData);
}
}
return treeDataList;
}
}
前端vue
主要使用到 lazy 懒加载
<template>
<div class="box">
<div class="leftBox">
<el-tree ref="myTree" :props="props" :load="loadNode" lazy node-key="id"></el-tree>
</div>
</div>
</template>
<script>
export default {
data() {
return {
props: {
label: "label",
isLeaf: "leaf",
},
};
},
methods: {
loadNode(node, resolve) {
//如果展开第一级节点,从后台加载一级节点列表(固定的)
if (node.level == 0) {
this.loadfirstnode(resolve);
}
//如果展开其他级节点,动态从后台加载下一级节点列表(可变的)
if (node.level >= 1) {
this.loadchildnode(node, resolve);
}
},
//加载第一级节点
async loadfirstnode(resolve) {
let params = {
};
const res = await this.$api.getTreeData(params);
return resolve(res);
},
//加载节点的子节点集合
async loadchildnode(node, resolve) {
// console.log("超过二级的", node, node.level);
let params = {
filePath: node.key,
};
const res = await this.$api.getTreeData(params);
return resolve(res);
},
},
};
</script>
<style lang="less" scoped>
.box {
width: 100%;
height: 600px;
box-sizing: border-box;
padding: 20px 0 0 10px;
border: 1px solid #e9e9e9;
display: flex;
.leftBox {
width: 40%;
box-sizing: border-box;
padding: 20px 20px 0 20px;
}
.rightBox {
width: 60%;
box-sizing: border-box;
padding-right: 10px;
}
}
</style>