对于网站而言,文件的存储从来都是问题。本人查找多个资料以后,得出了一个自认为可行的解决方案。
服务端:
数据库表
临时表
用于存放临时文件,可以定时清理
正式文件表
用于存放正式的文件
功能
采用java开发,nutz mvc,数据库为postgresql,文件系统为fastdfs,前端使用的树形插件为ztree
为什么是部分代码而不是全部代码?
因为用了fastdfs。用了nutz,用了ztree,也用了很多类库,所以剥离出来很麻烦,所以只把前台页面代码及后台处理逻辑贴出来意思意思。
前端主要js:
function sfilemgr(){ var fileMgrData={ tree_selectedNode:null, tree_selectedTid:0, tree_selectedId:0, Ztree:null, contextSource:"file", selectedFileId:0 }; var __getTreeNodeURL="/admin/sfilemgr/getFolders.jspx"; //--设定左侧的树形的事件。 //--用于动态构造url访问后台路径。 function getZTreeURL(treeId, treeNode){ if(treeNode==null){ return __getTreeNodeURL+"?t="+Math.random(); } return __getTreeNodeURL+"?id="+treeId+"&t="+Math.random(); } var ztree_setting = { view: { selectedMulti: false }, check: { enable: false }, async: { enable: true, url:getZTreeURL, autoParam:["id", "name=n", "level=lv"], otherParam:{"otherParam":"zTreeAsyncTest"}, dataFilter: filter }, callback: { beforeClick: beforeClick, beforeAsync: beforeAsync, onAsyncError: onAsyncError, onAsyncSuccess: onAsyncSuccess, beforeRightClick: zTreeBeforeRightClick, onRightClick: onRightClick//右键菜单。 } }; function zTreeBeforeRightClick(treeId, treeNode) { if(treeNode==null){ return; } fileMgrData.tree_selectedNode=treeNode; fileMgrData.tree_selectedId=treeNode.id; fileMgrData.tree_selectedTid=treeNode.tId; if (!treeNode && event.target.tagName.toLowerCase() != "button" && $(event.target).parents("a").length == 0) { fileMgrData.Ztree.cancelSelectedNode(); // showRMenu("root", event.clientX, event.clientY); } else if (treeNode && !treeNode.node) { fileMgrData.Ztree.selectNode(treeNode); // showRMenu("node", event.clientX, event.clientY); } return true; }; //--ztree的右键菜单。 function onRightClick(event, treeId, treeNode) { if(treeNode==null){ return; } showFolderContextMenu(event.pageX,event.pageY); } //--ztree 相关初始化 function filter(treeId, parentNode, childNodes) { if (!childNodes) return null; for (var i=0, l=childNodes.length; i<l; i++) { childNodes[i].name = childNodes[i].name.replace(/\.n/g, '.'); } return childNodes; } function beforeClick(treeId, treeNode) { fileMgrData.tree_selectedNode=treeNode; fileMgrData.tree_selectedId=treeNode.id; fileMgrData.tree_selectedTid=treeNode.tId; LoadFileList(); if (!treeNode.isParent) { //alert("请选择父节点"); return false; } else { return true; } } /** * 从服务器加载相关列表视图数据 * */ function LoadFileList(pageindex){ $.ajax({ url:"getPageFiles.jspx?directory="+fileMgrData.tree_selectedId+(pageindex!=undefined?("&pageindex="+pageindex):""), dataType:"json", error:function(p1,p2,p3){ alert("服务端错误!"); }, success:function(data){ if(data.status==false){ alert(data.message); return; } console.log(data); var html=generateFileItemHtml(data["list"]); $("#main_items").html(""); var _html=$(html); $("#main_items").append(_html); //--左键。 _html.find("a.the_file_item").click(function(){ $(this).toggleClass("selected"); }); //--右键。 function applyrule(menu) { if (this.id == "target2") { menu.applyrule({ name: "target2", disable: true, items: ["1-2", "2-3", "2-4", "1-6"] }); }else { menu.applyrule({ name: "all", disable: true, items: [] }); } } _html.find("a.the_file_item").mousedown(function(e){ if(3 == e.which){ //alert('这 是右键单击事件'); $("#main_items a.the_file_item").removeClass("selected"); $(this).addClass("selected"); }else if(1 == e.which){ //alert('这 是左键单击事件'); } }); _html.find("a.the_file_item").bind("contextmenu",function(e){ $("#main_items a.the_file_item").removeClass("selected"); $(this).addClass("selected"); fileMgrData.selectedFileId=parseInt($(this).attr("fileid")); showFileContextMenu(e.pageX, e.pageY); return false;}); //--添加右键菜单 //addFileItemOrFolderContenxtMenu(); //--分页。 $("#pagination").html(""); var jel=$("<div id='pager'></div>"); $("#pagination").append(jel); if(data["totalrecords"]>0){ jel.myPagination({ currPage:data["pageindex"], /*配置当前页面*/ pageCount: data["totalpages"], /*配置总页数*/ pageNumber: data["pagesize"], /*配置分页控件每次显示的页码方块个数*/ ajax: { /*点击事件*/ onClick: function (page) { var page_no = page; /*用户点击页码*/ LoadFileList(page_no); } /*点击事件结束*/ } }); } } }); } function generateFileItemHtml(JsonDataList){ var html = '<div>'; var json=JsonDataList; if (JsonDataList) { for (i = 0; i <JsonDataList.length; i++) { var name = ''; var filename = json[i]['name']; if(filename.length>15){ filename=filename.substr(0,15)+".."; } filename+="<br/>"; name+=filename; name += "<span class='sizearea'style='display:none;'>" + (JsonDataList[i]['size']/1024) + "kb</span>"; name += '<span class="filetimearea">' + json[i]['addtime'] + '</span>'; //alert(json[i]["thumb"]); var imgURL1= JsonDataList[i]['logo']; html += '<a class="the_file_item" fileid="'+JsonDataList[i]["id"]+'"><img width="100" height="100" class="file_item_img" src="' + imgURL1 + '" title="' + JsonDataList[i]['name'] + '" /><br />' + name + '</a>'; } } html += '</div>'; return html; } var log, className = "dark"; function beforeAsync(treeId, treeNode) { className = (className === "dark" ? "":"dark"); showLog("[ "+getTime()+" beforeAsync ] " + ((!!treeNode && !!treeNode.name) ? treeNode.name : "root") ); return true; } function onAsyncError(event, treeId, treeNode, XMLHttpRequest, textStatus, errorThrown) { showLog("[ "+getTime()+" onAsyncError ] " + ((!!treeNode && !!treeNode.name) ? treeNode.name : "root") ); } function onAsyncSuccess(event, treeId, treeNode, msg) { if(treeNode==undefined){ //--这是根节点。获取根节点。 var arr_nodes=fileMgrData.Ztree.getNodes(); if(arr_nodes!=null&&arr_nodes.length>0){ var theTid=arr_nodes[0].tId; //initFileItemOrFolderContextMenu("#"+theTid); } } else{ //--这不是根节点,获取下面的子节点。 if(treeNode.children!=null&&treeNode.children.length>0){ for(var index=0;index++;index<treeNode.length){ var _tid=treeNode.children[index].tId; // initFileItemOrFolderContextMenu("#"+_tid); } } } } function showLog(str) { if (!log) log = $("#log"); log.append("<li class='"+className+"'>"+str+"</li>"); if(log.children("li").length > 8) { log.get(0).removeChild(log.children("li")[0]); } } function getTime() { var now= new Date(), h=now.getHours(), m=now.getMinutes(), s=now.getSeconds(), ms=now.getMilliseconds(); return (h+":"+m+":"+s+ " " +ms); } function refreshNode(e) { var zTree = $.fn.zTree.getZTreeObj("treeDemo"), type = e.data.type, silent = e.data.silent, nodes = zTree.getSelectedNodes(); if (nodes.length == 0) { alert("请先选择一个父节点"); } for (var i=0, l=nodes.length; i<l; i++) { zTree.reAsyncChildNodes(nodes[i], type, silent); if (!silent) zTree.selectNode(nodes[i]); } } var ztree_inition_nodes=null; function __init_ztree(){ $.fn.zTree.init($("#folder_tree"),ztree_setting,null); $("#refreshNode").bind("click", {type:"refresh", silent:false}, refreshNode); $("#refreshNodeSilent").bind("click", {type:"refresh", silent:true}, refreshNode); $("#addNode").bind("click", {type:"add", silent:false}, refreshNode); $("#addNodeSilent").bind("click", {type:"add", silent:true}, refreshNode); fileMgrData.Ztree = $.fn.zTree.getZTreeObj("folder_tree"); } $(document).ready(function(){ __init_ztree(); }); //--ztree相关初始化 结束 //--新建文件夹逻辑 //$("#create").click(); var __handler_of_addFolder=function(){ if(fileMgrData.tree_selectedId==null||fileMgrData.tree_selectedNode==undefined){ alert("请在左侧文件夹目录树里面选择父文件夹"); return; } var treeObj=$.fn.zTree.getZTreeObj("folder_tree"); var selectedNode=treeObj.getNodeByTId(fileMgrData.tree_selectedTid); var nodes=treeObj.getCheckedNodes(true); if(selectedNode==null){ alert("请在左侧文件夹目录树里面选择父文件夹"); return; } var _theDialog= art.dialog({ title:"新建文件夹", lock:true, content:"<div><label>文件夹名称:</label><input id='txt_new_folder_name' name='foldername'></div>", ok:function(){ var _folderName= $.trim($("#txt_new_folder_name").val()); if(_folderName==""){ alert("请填写文件夹名称!"); return false; } var _ajax_url="create.jspx?pid="+selectedNode.id+"&foldername="+decodeURI(_folderName)+"&t="+Math.random(); $.ajax({ url:_ajax_url, dataType:"json", success:function(json){ if(json.status==false){ alert(json.message); return; } else{ _theDialog.close(); //--重新加载该节点的文件夹。 treeObj.reAsyncChildNodes(selectedNode, "refresh"); } }, error:function(){} // url }) ; return false; }, okVal:"确定", cancel:function(){}, cancelVal:"取消" }); }; //--编辑文件夹逻辑 //$("#folder_edit").click(); var __handler_of_editFolder=function(){ if(fileMgrData.tree_selectedTid==null||fileMgrData.tree_selectedTid==undefined){ alert("请在左侧文件夹目录树里面选择需要编辑的文件夹!"); return; } var treeObj=$.fn.zTree.getZTreeObj("folder_tree"); var selectedNode=treeObj.getNodeByTId(fileMgrData.tree_selectedTid); if(selectedNode==null){ alert("请在左侧文件夹目录树里面选择父文件夹"); return; } //--获得父目录的id。 var parentNode=selectedNode.getParentNode(); var pid=0; if(parentNode!=null){ pid=parentNode.id; } else{ alert("不允许修改根目录!"); return; } var _theDialog= art.dialog({ title:"编辑文件夹", lock:true, content:"<div><label>文件夹名称:</label><input id='txt_edit_folder_name' name='foldername'></div>", init:function(){ $("#txt_edit_folder_name").val(selectedNode.name); }, ok:function(){ var _folderName= $.trim($("#txt_edit_folder_name").val()); if(_folderName==""){ alert("请填写文件夹名称!"); return false; } var _ajax_url="edit_folder.jspx?pid="+pid+"&id="+selectedNode.id+"&foldername="+decodeURI(_folderName)+"&t="+Math.random(); $.ajax({ url:_ajax_url, dataType:"json", success:function(json){ if(json.status==false){ alert(json.message); return; } else{ _theDialog.close(); //--修改该节点状态 selectedNode.name=_folderName; treeObj.updateNode(selectedNode,false); //treeObj.reAsyncChildNodes(selectedNode, "refresh"); } }, error:function(){} // url }) ; return false; }, okVal:"确定", cancel:function(){}, cancelVal:"取消" }); }; //--添加文件 //$("#file_add").click(); var __handler_of_addFile=function(){ if(fileMgrData.tree_selectedId==null||fileMgrData.tree_selectedTid==undefined){ alert("请在左侧文件夹目录树里面选择需要编辑的文件夹!"); return; } var treeObj=$.fn.zTree.getZTreeObj("folder_tree"); var selectedNode=treeObj.getNodeByTId(fileMgrData.tree_selectedTid); if(selectedNode==null){ alert("请在左侧文件夹目录树里面选择父文件夹"); return; } //--获得父目录的id。 var parentNode=selectedNode.getParentNode(); var pid=0; if(parentNode!=null){ pid=parentNode.id; } var _theDialog= art.dialog({ title:"添加文件", lock:true, width:550, height:340, content:'<iframe id="iframe_add_file" src="/admin/sysfile/add.jspx?pid='+fileMgrData.tree_selectedId+'" style="padding:0; margin: 0; display: block; width:550px; height:340px;" frameborder="no" scrolling="auto"></iframe>', init:function(){ // $("#txt_edit_folder_name").val(selectedNode.name); }, ok:function(){ document.getElementById('iframe_add_file').contentWindow.add_handler(function(data){ console.log(data); LoadFileList(); _theDialog.close(); }); //alert("尚未处理逻辑"); return false; }, okVal:"确定", cancel:function(){}, cancelVal:"取消" }); }; //--编辑文件。 var __handler_of_editFile=function(){ var _theDialog= art.dialog({ title:"编辑文件", lock:true, width:550, height:340, content:'<iframe id="iframe_edit_file" src="/admin/sysfile/edit.jspx?id='+fileMgrData.selectedFileId+'" style="padding:0; margin: 0; display: block; width:550px; height:340px;" frameborder="no" scrolling="auto"></iframe>', init:function(){ // $("#txt_edit_folder_name").val(selectedNode.name); }, ok:function(){ document.getElementById('iframe_edit_file').contentWindow.edit_handler(function(data){ console.log(data); LoadFileList(); _theDialog.close(); }); //alert("尚未处理逻辑"); return false; }, okVal:"确定", cancel:function(){}, cancelVal:"取消" }); }; //--单独删除一个文件。 var __handler_of_deleteFile=function(){ var _theDialog2=art.dialog({ title:"警告", content:"是否删除该文件?【一旦删除文件将不可恢复】", lock:true, okValue:"删除", ok:function(){ $.ajax({ url:"/admin/sysfile/ajax_single_delete.jspx?id="+fileMgrData.selectedFileId, dataType:"json", success:function(data){ LoadFileList(); }, error:function(p1,p2,p3){ art.dialog({ title:"系统错误", content:""+p1 }); } }); return true; }, cancelValue:"取消", cancel:function(){} }); }; //--批量图片上传处理逻辑。 var __handler_of_mutiImg=function(){ var __totalCount=0;//图片计数器,计算总共多少图片 var __totalSuccess=0;//计算总共多少图片成功上传。 var __totalFailed=0;//计算总共多少图片上传失败。 var _currentDialog=null; _currentDialog= art.dialog({ title:"图片批量上传工具", lock:true, content:"<div style=' position: relative; width:850px;height:425px;' ><div style='width:1200px;height:425px; position: absolute; left:-350px;'><div id='content_muti_img' style='width:1400px;height:425px;'></div></div></div>", init:function(){ initUploadComponent(); } }); window.muti_img_perCallBack=function(jsonDataString){ return; } window.muti_img_callBack=function(){ if(_currentDialog!=null){ _currentDialog.close(); } LoadFileList(); } function initUploadComponent(){ var flashvars = { uploadUrl:"/admin/sfilemgr/multiUploadImg.jspx?folder="+fileMgrData.tree_selectedId,//上传图片的后台处理地址。 max:8,//最大上传图片张数。 allowDesc:true,//是否运行编辑图片描述 perCallBack:"muti_img_perCallBack",//js回调函数,请注意,这是其中一个图片上传完以后会调用的函数。注意区分。传进去的是服务端返回的字符串,需要自行处理字符串。 callBack:"muti_img_callBack",//js回调函数。请注意,这是所有图片都上传完毕以后回调的函数,注意,这个方法是调用完毕后才回调的,没有参数。 sequenceKey:"sequence",//发送文件时候,flash会向后台发送一个标识当前图片次序的参数,这个参数的key可以定制,默认为sequence,但是你也可以修改成为其他。 autoParaName:"folder", autoParaValue:fileMgrData.tree_selectedId }; var params = { menu: "false", scale: "noScale", allowFullscreen: "true", allowScriptAccess: "always", wmode:"transparent", bgcolor: "#FFFFFF" }; var attributes = { id:"FaustCplus" }; //swfobject.embedSWF("/static/UI/avatar/FaustCplus.swf", "altContent", "800", "500", "9.0.0", "expressInstall.swf", flashvars, params, attributes); // swfobject.embedSWF("/static/UI/avatar/FaulstCplusAS.swf", "altContent", "800", "500", "9.0.0", "expressInstall.swf", flashvars, params, attributes); swfobject.embedSWF("/static/UI/YUpload/YUploadImg.swf", "content_muti_img", "1200", "425", "9.0.0", "expressInstall.swf", flashvars, params, attributes); } } //_init_muti_upload_img(); //--批量上传文件处理逻辑 var __handler_of_mutiFile=function(){ var _currentDialog=null; _currentDialog= art.dialog({ title:"文件批量上传工具", lock:true, padding:0, content:"<div style='position: relative;width: 780px;height: 290px;overflow: hidden;'><div style='width:780px;height: 350px;position: absolute; top:-50px;' ><div id='content_muti_file'></div></div></div>", init:function(){ initUploadComponent(); } }); //--回调函数 window.muti_file_perCallBack=function(){ // console.log("单次成功。"); } window.muti_file_callBack=function(){ //alert("ok"); //_currentDialog.close(); // console.log("上传成功"); setTimeout(function(){ _currentDialog.close(); LoadFileList(); },100); } function initUploadComponent(){ var flashvars = { uploadUrl:"/admin/sfilemgr/multiUploadFile.jspx",//上传图片的后台处理地址。 MAX_NUM:12,//最大上传文件数量 perCallBack:"muti_file_perCallBack", callBack:"muti_file_callBack",//js回调函数。请注意,这是所有图片都上传完毕以后回调的函数,注意,这个方法是调用完毕后才回调的,没有参数。 showCount:8,//显示多少条待上传文件记录。 autoParaName:"folder", autoParaValue:""+fileMgrData.tree_selectedId }; var params = { menu: "false", scale: "noScale", allowFullscreen: "true", allowScriptAccess: "always", wmode:"transparent", bgcolor: "#FFFFFF" }; var attributes = { id:"muti_file_uploader" }; swfobject.embedSWF("/static/UI/mutiupload/FileUpload.swf", "content_muti_file", "780", "450", "9.0.0", "expressInstall.swf", flashvars, params, attributes); } } /** * 各种菜单 * */ /** * 这是文件夹的右键菜单。 * */ function initFolderContextMenu(){ $.contextMenu({ selector: '#hidden_div', callback: function(key, options) { var m = "clicked: " + key; if(key=="delete"){ alert("系统暂时不支持删除任何文件目录!"); return; } if(key=="view"){ LoadFileList(); return; } if(key=="add"){ __handler_of_addFolder(); return; } if(key=="edit"){ __handler_of_editFolder(); return; } if(key=="add_file"){ __handler_of_addFile(); return; } if(key=="add_muti_img"){ __handler_of_mutiImg(); return; } if(key=="add_muti_file"){ __handler_of_mutiFile(); return; } }, items: { "view":{name:"查看列表",icon:"/public/icons/view_16x16.png"} , "sep1": "---------", "add_file":{name:"添加文件",icon:""}, "add_muti_img":{name:"批量添加图片",icon:""}, "add_muti_file":{name:"批量上传文件",icon:""}, "sep2": "---------", "add":{name:"添加子目录",icon:"add"}, "edit": {name: "编辑文件夹", icon: "edit"}, "delete": {name: "删除目录", icon: "cut"}, "sep3": "---------", "quit": {name: "退出", icon: "quit"} } }); } initFolderContextMenu(); function showFolderContextMenu(x,y){ $("#hidden_div").css({"left":x+"px","top":y+"px"}); $("#hidden_div").contextMenu(); } function initFileContextMenu(){ $.contextMenu({ selector: '#hidden_div_file_menu', callback: function(key, options) { if(key=="edit"){ __handler_of_editFile(); return; } if(key=="delete"){ __handler_of_deleteFile(); return; } var m = "clicked: " + key; window.console && console.log(m) || alert(m); }, items: { "edit": {name: "编辑文件", icon: "edit"}, //"cut": {name: "Cut", icon: "cut"}, //"copy": {name: "Copy", icon: "copy"}, "sep1": "---------", "delete": {name: "删除", icon: "delete"}, "sep2": "---------", "quit": {name: "退出", icon: "quit"} } }); } initFileContextMenu(); function showFileContextMenu(x,y){ $("#hidden_div_file_menu").css({"left":x+"px","top":y+"px"}); $("#hidden_div_file_menu").contextMenu(); } }
后台主要java代码:
package EWeb.Controller.admin; import java.util.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import EWeb.Base.BLL.FileDirectoryBLL; import EWeb.Base.BLL.FileSysBLL; import EWeb.Base.DAL.ApplyFreightDAL; import EWeb.Base.DAL.SysFileDAL; import EWeb.Base.DAL.filedirectoryDAL; import EWeb.Base.Model.SysFileModel; import EWeb.Base.Model.filedirectoryModel; import EWeb.Base.Model.memberModel; import EWeb.Base.OpModel.SysFileOp; import EWeb.Base.OpModel.applySearchCondition; import EWeb.Filters.CheckAdminLogin; import EWeb.RedisSess.RSession; import EWeb.RedisSess.SessionManager; import EWeb.UI.ErrorPage; import EWeb.UI.FileMGR; import Easis.Common.HtmlCleaner; import Easis.Common.Validation; import Easis.Media.FileType; import Easis.Media.FileTypeHelper; import Easis.util.DataRow; import Easis.util.DataTable; import Easis.util.PagerResult; import Easis.HTTP.RequestEX; import Easis.util.OperationResult; import Easis.Common.JsonHelper; import Easis.Common.StringUtil; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.nutz.mvc.View; import org.nutz.mvc.annotation.*; import org.nutz.mvc.annotation.Param; import EWeb.Base.DAL.ApplyFreightDAL; import EWeb.Base.Model.ApplyFreightModel; import org.apache.log4j.Logger; import org.nutz.mvc.view.JspView; import org.nutz.mvc.view.RawView; import org.nutz.mvc.view.ViewWrapper; /** * 管理中心模板。 * 这是利用CodeGen工具生成的控制器的一个模板,作者为“码农下的天桥” * 生成的类名称: * @author 码农下的天桥 * @version 1.00 */ @At("/admin/sfilemgr/") @Filters(@By(type = CheckAdminLogin.class)) public class sfilemgrController { @At("/index") @Ok("jsp:jsp.admin.sfilemgr.index") public void index(){ } @At("/getFolders") @Ok("raw") public String getFolders(HttpServletRequest request){ RequestEX _req=new RequestEX(request); int theID=StringUtil.toInt(_req.getParaValueByBoth("id")); filedirectoryDAL _dal=new filedirectoryDAL(); JSONArray _arr=new JSONArray(); if(theID<=0){ filedirectoryModel _model= _dal.GetRecord(2); JSONObject _obj=new JSONObject(); _obj.put("id",_model.id); _obj.put("name",_model.name) ; _obj.put("isParent",true); //_obj.put("") //_arr.add(_model); _arr.add(_obj); } else{ DataTable dt= _dal.getTopNByCondition(100,"*","where pid="+theID,""); if(dt.getRows().size()>0){ filedirectoryModel _tmpModel=new filedirectoryModel(); for(DataRow drow:dt.getRows()){ _tmpModel=_dal.tryParseModel(drow); JSONObject _tmpJson=new JSONObject(); _tmpJson.put("isParent",true); _tmpJson.put("id",_tmpModel.id); _tmpJson.put("name",_tmpModel.name); _arr.add(_tmpJson); } } } return JSON.toJSONString(_arr); } @At("/create") @Ok("raw") public String createNewFolder(HttpServletRequest request){ RequestEX _req=new RequestEX(request); String _strName=HtmlCleaner.getPlainText(_req.getParaValueByBoth("foldername")); int _thepid=StringUtil.toInt(_req.getParaValueByBoth("pid")); OperationResult _op=new OperationResult(); if(StringUtil.isNullOrEmpty(_strName)){ _op.status=false; _op.message="必须填写文件夹名称!"; return JSON.toJSONString(_op.toHashtable()); } if(_thepid<=0){ _op.status=false; _op.message="请指定父目录!"; return JSON.toJSONString(_op.toHashtable()); } filedirectoryDAL _dal=new filedirectoryDAL(); filedirectoryModel _model=new filedirectoryModel(); _model.pid=_thepid; _model.name=_strName; _op= _dal.Insert(_model); return JSON.toJSONString(_op.toHashtable()); } @At("/edit_folder") @Ok("raw") public String editFolder(HttpServletRequest request){ RequestEX _req=new RequestEX(request); String _strName=HtmlCleaner.getPlainText(_req.getParaValueByBoth("foldername")); int _theid=StringUtil.toInt(_req.getParaValueByBoth("id")); OperationResult _op=new OperationResult(); if(StringUtil.isNullOrEmpty(_strName)){ _op.status=false; _op.message="必须填写文件夹名称!"; return JSON.toJSONString(_op.toHashtable()); } if(_theid<=0){ _op.status=false; _op.message="请指定需要修改的目录!"; return JSON.toJSONString(_op.toHashtable()); } int _thepid=StringUtil.toInt(_req.getParaValueByBoth("pid")); filedirectoryDAL _dal=new filedirectoryDAL(); filedirectoryModel _model=new filedirectoryModel(); _model.pid=_thepid; _model.name=_strName; _model.id=_theid; _op= _dal.Update(_model); return JSON.toJSONString(_op.toHashtable()); } /** * 获得当前目录下面所有文件。注意:这个没有分页。 * 请用getPageFile代替。 * */ @At("/getFiles") @Ok("raw")public String getFiles(HttpServletRequest request){ RequestEX req=new RequestEX(request); int theDirectory=StringUtil.toInt(req.getParaValueByBoth("directory")); JSONObject _json=new JSONObject(); if(theDirectory<=0){ _json.put("status",false); _json.put("message","目录id不合法!"); return JSON.toJSONString(_json); } SysFileDAL _dal=new SysFileDAL(); DataTable dtable= _dal.Top_Condition(99,"*","where directory="+theDirectory,"order by addtime desc"); List<SysFileModel> _files=_dal.tryParseList(dtable.getRows()); JSONArray _arr_files=new JSONArray(); for(SysFileModel _model:_files){ JSONObject _obj1=new JSONObject(); _obj1.put("id",_model.id); _obj1.put("addtime",StringUtil.FormatDateTime(_model.addtime,"yyyy-MM-dd")); _obj1.put("edittime",StringUtil.FormatDateTime(_model.editime,"yyyy-MM-dd")); _obj1.put("ext",_model.ext); _obj1.put("directory",_model.directory); _obj1.put("filetype",_model.filetype); _obj1.put("name",_model.name); _obj1.put("remark",_model.remark); _obj1.put("logo", FileMGR.getFileLogoPath(FileTypeHelper.str2FileType(_model.ext),_model.id,false)); _arr_files.add(_obj1); } _json.put("status",true); _json.put("message",""); _json.put("list",_arr_files); return JSON.toJSONString(_json); } /** * 获得后台文件的分页列表。 * */ @At("/getPageFiles") @Ok("raw")public String getPageFiles(HttpServletRequest request){ RequestEX req=new RequestEX(request); int theDirectory=StringUtil.toInt(req.getParaValueByBoth("directory")); JSONObject _json=new JSONObject(); if(theDirectory<=0){ _json.put("status",false); _json.put("message","目录id不合法!"); return JSON.toJSONString(_json); } int pagesize=20; int totalCount=20; int pageindex=StringUtil.toInt(req.getParaValueByBoth("pageindex")); int _pageindex=pageindex<=0?1:pageindex; PagerResult pagerInfo=new PagerResult(); SysFileDAL _dal=new SysFileDAL(); pagerInfo= _dal.getPageListByCondition(pageindex,pagesize,"*","where directory="+theDirectory,"order by addtime desc"); //DataTable dtable= _dal.Top_Condition(99,"*","where directory="+theDirectory,"order by addtime desc"); List<SysFileModel> _files=_dal.tryParseList(pagerInfo.datasource.getRows()); JSONArray _arr_files=new JSONArray(); for(SysFileModel _model:_files){ JSONObject _obj1=new JSONObject(); _obj1.put("id",_model.id); _obj1.put("addtime",StringUtil.FormatDateTime(_model.addtime,"yyyy-MM-dd")); _obj1.put("edittime",StringUtil.FormatDateTime(_model.editime,"yyyy-MM-dd")); _obj1.put("ext",_model.ext); _obj1.put("directory",_model.directory); _obj1.put("filetype",_model.filetype); _obj1.put("name",_model.name); _obj1.put("remark",_model.remark); _obj1.put("logo", FileMGR.getFileLogoPath(FileTypeHelper.str2FileType(_model.ext),_model.id,false)); _arr_files.add(_obj1); } _json.put("status",true); _json.put("message",""); _json.put("list",_arr_files); _json.put("pagesize",pagerInfo.pagesize); _json.put("pageindex",pagerInfo.pageindex); _json.put("totalrecords",pagerInfo.totalrecords); _json.put("totalpages",pagerInfo.totalpages); return JSON.toJSONString(_json); } /** * 对前台的批量上传图片进行处理。 * 接收其中一个图片及信息。 * */ @At("/multiUploadImg") @Ok("raw") public String multiUploadImg(HttpServletRequest request){ int FolderId=0; String desc=""; String fileName=""; Hashtable<String,Object> _hash=new Hashtable<String, Object>(); DiskFileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); upload.setHeaderEncoding("utf-8"); try { Hashtable<String,String> _queryHash= RequestEX.parseQueryString(request.getQueryString()); if(_queryHash.containsKey("folder")){ FolderId=StringUtil.toInt(_queryHash.get("folder")); } List items = upload.parseRequest(request); Iterator itr = items.iterator(); FileItem _fileItem=null; while (itr.hasNext()) { FileItem item = (FileItem) itr.next(); if (item.isFormField()) { if(item.getFieldName().equals("Filename")){ fileName=StringUtil.decodeURI(item.getString()); fileName=HtmlCleaner.getPlainText(fileName) ; fileName=StringUtil.cutStr(fileName,45,".."); } else if(item.getFieldName().equals("desc")){ desc=StringUtil.decodeURI(item.getString()); desc=StringUtil.cutStr(HtmlCleaner.getPlainText(desc),45,".."); } // System.out.println("表单参数名:" + item.getFieldName() + ",表单参数值:" + item.getString("UTF-8")); } else { if (item.getName() != null && !item.getName().equals("")) { _fileItem=item; }else{ } } } if(_fileItem==null){ _hash.put("status",false); _hash.put("message","没有上传任何文件!"); _hash.put("url",""); return JSON.toJSONString(_hash); } if(FolderId<=0){ _hash.put("status",false); _hash.put("message",String.format("文件 %s 没有指定保存目录!",fileName)); _hash.put("url",""); return JSON.toJSONString(_hash); } //--保存图片 byte[] _fileContent= _fileItem.get(); SysFileOp _sfileOp=new SysFileOp(); FileType _type=FileTypeHelper.getFileType(_fileContent); _sfileOp= FileSysBLL.AddSysFile(fileName, desc, FileMGR.getDBFileTyp(_type), FolderId, _fileContent); if(_sfileOp.status==false){ _hash.put("status",false); _hash.put("message",_sfileOp.message); _hash.put("url", FileMGR.getFileLogoPath(_type, _sfileOp.model.id, false)); return JSON.toJSONString(_hash); } _hash.put("status",true); _hash.put("message","成功上传图片!"); _hash.put("url", FileMGR.getFileLogoPath(_type, _sfileOp.model.id, false)); return JSON.toJSONString(_hash); }catch(FileUploadException e){ e.printStackTrace(); _hash.put("status",false); _hash.put("message","上传文件失败,文件流异常!"); _hash.put("url",""); return (JSON.toJSONString(_hash)); } catch (Exception e) { e.printStackTrace(); _hash.put("status",false); _hash.put("message","服务器500错误!"); _hash.put("url",""); return (JSON.toJSONString(_hash)); } } /** * 对前台的批量上传图片进行处理。 * 接收其中一个图片及信息。 * */ @At("/multiUploadFile") @Ok("raw") public String multiUploadFile(HttpServletRequest request){ int FolderId=0; String desc=""; String fileName=""; Hashtable<String,Object> _hash=new Hashtable<String, Object>(); DiskFileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); upload.setHeaderEncoding("utf-8"); try { List items = upload.parseRequest(request); Iterator itr = items.iterator(); FileItem _fileItem=null; while (itr.hasNext()) { FileItem item = (FileItem) itr.next(); if (item.isFormField()) { if(item.getFieldName().equals("Filename")){ String str1=item.getString(); fileName=StringUtil.decodeURI(item.getString()); fileName=HtmlCleaner.getPlainText(fileName) ; fileName=StringUtil.cutStr(fileName,45,".."); } else if(item.getFieldName().equals("desc")){ desc=StringUtil.decodeURI(item.getString()); desc=HtmlCleaner.getPlainText(desc); } else if(item.getFieldName().equals("folder")){ FolderId=StringUtil.toInt(item.getString()); } // System.out.println("表单参数名:" + item.getFieldName() + ",表单参数值:" + item.getString("UTF-8")); } else { if (item.getName() != null && !item.getName().equals("")) { _fileItem=item; }else{ } } } if(_fileItem==null){ _hash.put("status",false); _hash.put("message","没有上传任何文件!"); _hash.put("url",""); return JSON.toJSONString(_hash); } if(FolderId<=0){ _hash.put("status",false); _hash.put("message",String.format("文件 %s 没有指定保存目录!",fileName)); _hash.put("url",""); return JSON.toJSONString(_hash); } //--保存图片 byte[] _fileContent= _fileItem.get(); SysFileOp _sfileOp=new SysFileOp(); FileType _type=FileTypeHelper.getFileType(_fileContent); _sfileOp= FileSysBLL.AddSysFile(fileName, desc, FileMGR.getDBFileTyp(_type), FolderId, _fileContent); if(_sfileOp.status==false){ _hash.put("status",false); _hash.put("message",_sfileOp.message); _hash.put("url", FileMGR.getFileLogoPath(_type, _sfileOp.model.id, false)); return JSON.toJSONString(_hash); } _hash.put("status",true); _hash.put("message","成功上传文件!"); _hash.put("url", FileMGR.getFileLogoPath(_type, _sfileOp.model.id, false)); return JSON.toJSONString(_hash); }catch(FileUploadException e){ e.printStackTrace(); _hash.put("status",false); _hash.put("message","上传文件失败,文件流异常!"); _hash.put("url",""); return (JSON.toJSONString(_hash)); } catch (Exception e) { e.printStackTrace(); _hash.put("status",false); _hash.put("message","服务器500错误!"); _hash.put("url",""); return (JSON.toJSONString(_hash)); } } }