具体要求
展示文件树状结构,普通文件在前,文件夹在后,文件夹没有内容则不可点击
技术支持
Python 代码
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#a test for traverse directory
from flask import Flask,request
import json
import os
import os.path
def dfs_showdir(path):
# 定义两个数组 分别存文件夹和普通文件 普通文件在前 文件夹在后
a = [];
c = [];
# 遍历根目录
for item in os.listdir(path):
b = {};
b['title'] = item;
newitem = path +'/'+ item;
if os.path.isdir(newitem):
b['children'] = dfs_showdir(newitem); # 获取子节点
# 区分文件和普通文件
if 'children' in b.keys():
if b['children'] == []:
b['disabled'] = 'true'; # 子节点为空不可点击
a.append(b);
else:
c.append(b);
return c + a
app = Flask(__name__)
# 只接受get方法访问
@app.route("/", methods=["GET"])
def main():
get_data = request.args.to_dict()
path = get_data.get('path')
return json.dumps(dfs_showdir(path), ensure_ascii=False), 200, [('Access-Control-Allow-Origin', '*')]
if __name__ == "__main__":
app.run(host="0.0.0.0", debug=True)
HTML代码
<link rel="stylesheet" href="https://www.layuicdn.com/layui/css/layui.css" media="all">
<fieldset class="layui-elem-field layui-field-title" style="margin-top: 30px;">
<legend>常规用法</legend>
</fieldset>
<div id="test1" class="demo-tree demo-tree-box"></div>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="https://www.layuicdn.com/layui/layui.js" charset="utf-8"></script>
<script>
layui.use(['tree'], function() {
var tree = layui.tree
// 请求后端接口
$.get('http://192.168.222.128:5000?path=./aaaa', function (res) {
// 组件初始化
tree.render({
elem: '#test1',
data: res
});
},'json');
})
</script>
目录结构及实现效果