需求: 服务器上有一个文件夹(根文件夹),其下面有可能是文件也有可能是文件夹且文件夹下面又有文件以及文件夹。
1 要求以树状结构展示这些文件,且可以选择不同文件夹下面的多个文件,所以叶子节点要加checkbox,且文件夹不加;
2 选择文件的时候要对文件内容进行预览。
下面是具体实现
1 Model定义:
Ext.define('Qui.model.TestAsset', {
extend: 'Ext.data.Model',
requires: [
'Ext.data.Field'
],
idProperty: 'path',
fields: [
{
name: 'assetId'
},
{
name: 'factoryId'
},
{
name: 'name'
},
{
name: 'path'
},
{
name: 'listName'
}
]
});
2 Store定义:
Ext.define('Qui.store.TestAsset', {
extend: 'Ext.data.TreeStore',
requires: [
'Qui.model.TestAsset',
'Ext.data.proxy.Ajax',
'Ext.data.reader.Json'
],
constructor: function(cfg) {
var me = this;
cfg = cfg || {};
me.callParent([Ext.apply({
model: 'Qui.model.TestAsset',
storeId: 'testAsset',
nodeParam: 'path',
proxy: {
type: 'ajax',
url: 'getTestAssets.action',
reader: {
type: 'json',
idProperty: 'path'
}
},
listeners: {
load: {
fn: me.onTreeStoreLoad,
scope: me
}
}
}, cfg)]);
},
onTreeStoreLoad: function(treestore, node, records, successful, eOpts) {
if(successful){
var rootPath;
if(records !== null){
var childPath = records[0].get('path');
if(!Ext.isEmpty(childPath) && childPath.lastIndexOf('/')>0){
rootPath = childPath.substr(0,childPath.lastIndexOf('/'));
}
}
if(node.get('path') === 'root'){
node.set('name', rootPath !== null ? rootPath : 'Root');
}else{
//这里是实现checkbox tree的关键,节点的cls属性是folder的时候,设置checked属性为false:即文件夹不能被选中,只能选中文件。
Ext.Array.each(records,function(record){
if(record.get('cls') !== 'folder'){
record.set('checked', false);
}
});
}
}
}
});
3 后台AssetTreeNode VO model的结构(省略get/set):
private static final String FOLDER_CLASS = "folder";
private String assetId;
private List<AssetTreeNode> children;
private String factoryName;
private boolean leaf;
private String name;
private String path;
private String cls;
//静态方法,将file转换为TreeNode
public static AssetTreeNode fromFile(final File file) {
assert file != null && file.exists() : "File does not exist: " + file;
final AssetTreeNode node = new AssetTreeNode();
if (file.isFile()) {
node.setLeaf(true);
} else {
node.setCls(FOLDER_CLASS);
}
final String name = file.getName();
node.setName(name);
node.setAssetId(name);
node.setPath(file.getPath());
return node;
}
4 点击叶节点的时候privewpanel加载文件内容
onAssetTreePanelItemClick: function(dataview, record, item, index, e, eOpts) {
var filepath = record.get('path');
var previewPanel = dataview.up('window').down('#testAssetPreview');
if(record.isLeaf()){//只有叶节点即文件才可预览
Ext.Ajax.request({
url:'reports/taskdetail/getFileContent.action',
params: {filename: filepath},
scope: this,
success: function(response, opts){
var result = Ext.decode(response.responseText);
previewPanel.setValue(result.fileContent);
},
failure: function(response, opts){
this.application.showFailure();
}
});
}
return false;
}
5 效果图