namespace ejk.com
{
public class FileNames
{
public int id { get; set; }
public string text { get; set; }
public state state { get; set; }
public List<FileNames> children { get; set; }
public string icon { get; set; }
}
public class state
{
public bool opened { get; set; }
}
//以上字段为树形控件中需要的属性
public class GetSystemAllPath : Controller
{
//获得指定路径下所有文件名
public static List<FileNames> getFileName(List<FileNames> list, string filepath)
{
DirectoryInfo root = new DirectoryInfo(filepath);
foreach (FileInfo f in root.GetFiles())
{
list.Add(new FileNames
{
text = f.Name,
state = new state { opened = false },
icon = "jstree-file"
});
}
return list;
}
//获得指定路径下的所有子目录名
// <param name="list">文件列表</param>
// <param name="path">文件夹路径</param>
public static List<FileNames> GetallDirectory(List<FileNames> list, string path) {
DirectoryInfo root = new DirectoryInfo(path);
var dirs = root.GetDirectories();
if (dirs.Count()!=) {
foreach (DirectoryInfo d in dirs)
{
list.Add(new FileNames
{
text = d.Name,
state = new state { opened = false },
children = GetallDirectory(new List<FileNames>(), d.FullName)
});
}
}
list = getFileName(list, path);
return list;
}
}
}
以上为核心部分!!!
后台返回代码:Sample/GetAllPath
[HttpGet("[action]")]
public List<FileNames> GetAllPath() {
//获取当前系统的根路径
string rootpath = $"{hostingEnv.ContentRootPath}/";
var list = GetSystemAllPath.GetallDirectory(new List<FileNames>(), rootpath).ToArray();
return list.ToList();
}
前台Html:
<div id="demo"></div>
js部分:
$('#demo')
//jstree listen for event
.on('changed.jstree', function (e, data) {
if (data && data.selected && data.selected.length) {
$('#selectpath').val(data.instance.get_path(data.selected[0], "/", 0));
} else {
$('#selectpath').val('Select a file from the tree.');
}
}).jstree({
'core': {
'data': {
"url": "api/Sample/GetAllPath",
"data": function (node: any) {
return { "id": node.id };
}
}
}
});
前端树形控件使用的是jstree,具体使用方法可以见其官网:https://www.jstree.com/
最后贴上效果图:
Copyright © 广州京杭网络科技有限公司 2005-2024 版权所有 粤ICP备16019765号
广州京杭网络科技有限公司 版权所有