码迷,mamicode.com
首页 > Web开发 > 详细

struts2文件上传例子

时间:2016-05-06 16:13:15      阅读:307      评论:0      收藏:0      [点我收藏+]

标签:

package com.fm.action;
import java.sql.*;
import org.apache.struts2.ServletActionContext;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Writer;<pre name="code" class="javascript">	var user_name='<%=username %>'; 
	var htmldata = "";
	var defultHtmlData = "";
	var defultData = [];
	var defultQueryHtml = "";
	var autoloadcontrol;
	var idList = "";
	var nowCm;
	var store;
	var store1;
	var selectedTableName = "";
	var selectedUpTableName = "";
	var selectedTypeList = "";
	var selectedUpTypeList = "";
	var upIdList = "";
	var upValueList = "";
	var fields = [];
	var rdItems = [];
    var rdConfig = {};
    var grids;
  	var curWwwPath=window.document.location.href;
	var pathName=window.document.location.pathname;
	var pos=curWwwPath.indexOf(pathName);
	var localhostPaht=curWwwPath.substring(0,pos);
	var projectName=pathName.substring(0,pathName.substr(1).indexOf('/')+1);
	var baseUrl = localhostPaht + projectName;
	var viewFile;
	
	var page_size = 15;//查询列表每一页显示数据条数
	var maxSize="20971520";//附件上传大小限制 1M=1048576字节
	var allowUploadFile =["jpg","gif","png","bmp","jpeg","pdf","doc","docx","xls","xlsx","ppt","ceb","txt"]; //允许上传的文件类型
	
	var link = {
	getTreeData : baseUrl + "/pages/fm_getTreeData.do",
	formQuery : baseUrl + "/pages/fm_formQuery.do",
	getformQueryData : baseUrl + "/pages/fm_getConditionData.do",
	getFileList : baseUrl + "/pages/fm_getFileList.do",
	getDefultData : baseUrl + "/pages/fm_getDefultData.do",
	getAllDataRead : baseUrl + "/pages/fm_getAllDataRead.do",
	delFile : baseUrl + "/pages/fm_delFile.do",
	getOffice2HtmlPath : baseUrl + "/pages/fm_getOffice2HtmlPath.do",
	uploadFile : baseUrl + "/pages/up_upload.do"
	};
	
	 	function getDefultData(){//打开页面时,获得全局条件
			$.ajax({
	     	     type:"POST",
	     	     url: link.getDefultData,
	     	     success:function(data){
	     	    	 if(data[0].name=="err"){
		     	    	 try{
		     	    	 	Ext.getCmp("toppanel").body.update("<form name=\"queryform\" id=\"queryform\" action=\""+link.formQuery+"\" method=\"post\"></form>");
		     	    	 }catch(e){
		     	    	 }
	     	    		return;
	     	    	 }
	     	    	 defultData = [];
	     	    	 for(var i=0;i<data.length;i++){
	     	    	 	defultData.push(data[i]);
	     	    	 }
	     	    	 setDefultQueryHtml(data);//设置显示全局条件
	     	     },
	     	     dataType:"json"
	  	});
	}
	
	
	function setDefultQueryHtml(data){//打开页面时 显示全局条件
		defultQueryHtml = "";
			for(var i=0;i<data.length;i++){
				defultQueryHtml += "<div class=\"formdiv\"><div class=\"textdiv\">"+data[i].name+":</div>";
				defultQueryHtml += "<input name=\""+data[i].enname+"\" id=\""+data[i].enname+"\" text=\""+data[i].name+"\" class=\"valuediv\" type=\"text\"/></div>"
			}
			defultHtmlData = "<form name=\"queryform\" id=\"queryform\" action=\""+link.formQuery+"\" method=\"post\">"+defultQueryHtml+"</form>";
			Ext.getCmp("toppanel").body.update(defultHtmlData);
	}
	
	function delFile(){
		    var guid = grids.getSelectionModel().getSelected().get("guid");
		    var fileType = grids.getSelectionModel().getSelected().get("type");
		    var delFileName = grids.getSelectionModel().getSelected().get("filename");
		    if(confirm("确认删除 " + delFileName +" 吗?")){
	        	$.ajax({
	          	     type: 'POST',
	          	     url: link.delFile,
	          	     data:{guid:guid,type:fileType,table:selectedTableName},
	          	     success:function(data){
	          		 if(data=="true"){
	          		     grids.getStore().remove(grids.getSelectionModel().getSelected());
	          		     alert("删除成功");
	          		 }else{
	          		     alert("删除失败");
	          		 	}
	          	     },
	          	     dataType:"text"
	       	});
		    }
		}
	

Ext.onReady(function(){

	Ext.QuickTips.init();

	Ext.form.Field.prototype.msgTarget = "side";
	
	
		viewFile =function(){
			var guid = grids.getSelectionModel().getSelected().get("guid");
		    var fileType = grids.getSelectionModel().getSelected().get("type");
		    var FileName = grids.getSelectionModel().getSelected().get("filename");
		    var htmlPath = "";
		    var t = "";
		    if(fileType=="JPG"||fileType=="PNG"||fileType=="JPEG"||fileType=="GIF"||fileType=="BMP"){
				t = 1;//图片格式
				openViewWin(FileName,fileType,guid,t,htmlPath);
			}else if(fileType=="TXT"){
				t = 2;//文本格式
				openViewWin(FileName,fileType,guid,t,htmlPath);
			}else if(fileType=="PDF"){
				t = 4;//PDF格式
				openViewWin(FileName,fileType,guid,t,htmlPath);
			}else if(fileType=="DOC"||fileType=="DOCX"||fileType=="XLS"||fileType=="XLSX"){
				t = 3//word,excel格式
				viewMask.show()
				$.ajax({
		     	     type:"POST",
		     	     url: link.getOffice2HtmlPath,
		     	     data:{type:fileType,guid:guid},
		     	     success:function(data){
		     	     	if(data=="err"){
		     	     		alert("预览失败")
		     	     		viewMask.hide();
		     	     		return;
		     	     	}else{
		     	     		viewMask.hide()
		     	     		htmlPath = data;
		     	     		openViewWin(FileName,fileType,guid,t,htmlPath);
		     	     	}
		     	     },
		     	     dataType:"text"
		  	});
			}else{
				alert("此格式不支持在线浏览")
				return;
			}
		}
		
		 var viewMask = new Ext.LoadMask(Ext.getBody(),{    
              msg:"正在打开文件请稍后...",
              removeMask:true
          }); 
		
		function openViewWin(FileName,fileType,guid,t,htmlPath){
			var awidth = document.body.clientWidth-65;
			var aheight = document.body.clientHeight-115;
			var filePath = baseUrl+"/AffixFiles/FileManager/"+guid+"."+fileType;
			var hd;
			if(t=="1"){//图片格式
				hd = "<img src="+filePath+">";
			}else if(t=="2"){//文本格式
				hd = "<iframe src="+filePath+" name=iframe1 width="+awidth+" height="+aheight+"></iframe>";
			}else if(t=="3"){//word
				hd = "<iframe src="+htmlPath+" name=iframe1 width="+awidth+" height="+aheight+"></iframe>";
			}else if(t=="4"){//PDF
				hd = "<iframe src="+filePath+" name=iframe1 width="+awidth+" height="+aheight+"></iframe>";
			}
			var viewPanel = new Ext.Panel({
			id:"viewPanel",
            border:true,
            autoScroll:true,
            layout:"anchor",
            width:document.body.clientWidth-45,
            height:document.body.clientHeight-95,
            frame:true,
            html:hd
      })
		
			var viewWin = new Ext.Window({
			 		title :"文件预览:  "+FileName+"."+fileType.toLowerCase(),
				    id : 'viewWin',
				    border : false,
				    draggable:false,
			    	resizable:false,
				    width : document.body.clientWidth-30,
				    height : document.body.clientHeight-30,  
				    plain : true,
				    modal : true,
				    buttonAlign:'center',
				    items:[viewPanel],
				     buttons:[{
			     	text: '关闭',
                    handler: function(){
                    	viewWin.close()
                    }}]
				    })
					viewWin.show()
		}
		
	
		function selectUptree(){
			try{
				var path = mytree.getSelectionModel().getSelectedNode().getPath();
				Ext.getCmp("mytree1").selectPath(path);
				var node = Ext.getCmp("mytree1").getSelectionModel().getSelectedNode();
				if(node.attributes.text!="附件分类"){
					getUpFatherNodeList(node);
					autoloadcontrol.body.update("");
					setUploadForm(node.attributes.id);
				}
			}catch(e){
				return;
			}
		}
		
		function dt(){//根据所选分类刷新列表表头
			var idListArr = idList.split("|");
			var cmItems = [];
 			var cmConfig = {};
 			cmItems.push(new Ext.grid.RowNumberer());
 			cmItems.push({id:'id', header: "id", width: 100,hidden:true, hideable:false,sortable: false, dataIndex: 'id',renderer:tips});
 			cmItems.push({id:'filename', header: "附件名称", width: 200, sortable: false, dataIndex: 'filename',renderer:tips});
				try{
					var form=document.getElementById("queryform");
					for(var i=0;i<form.length;i++){
						if (form[i].type == "text"){
							var cmConfig = {id:form[i].name,header:form[i].text,width:100,sortable:false,dataIndex:form[i].name,renderer:tips};
							cmItems.push(cmConfig);
						}
					}
				}catch(e){
				}
			cmItems.push({id:'type', header: "附件类型", width: 50, sortable: false, dataIndex: 'type',renderer:tips});
			cmItems.push({id:'filepath', header: "文件路径", width: 0,hidden:true, sortable: false,hideable:false, dataIndex: 'filepath',renderer:tips});
			cmItems.push({id:'guid', header: "guid", width: 0,hidden:true, sortable: false,hideable:false, dataIndex: 'guid',renderer:tips});
			cmItems.push({id:'types', header: "types", width: 0,hidden:true, sortable: false,hideable:false, dataIndex: 'types',renderer:tips});
			cmItems.push(time);
			cmItems.push(cz);
			sm = new Ext.grid.ColumnModel(cmItems);
			grids.reconfigure(store,sm);
		}
		
		function setUpData(){//获得上传时form表单中的控件ID与填写内容
		upIdList = "";
		upValueList = "";
		var form = Ext.getCmp("fp").getForm();
			for(var i=0;i<form.items.items.length;i++){
				if (form.items.items[i].id != "form-file"){
					upIdList += form.items.items[i].name+"|";
					if(form.items.items[i].getValue().trim()==""){
						upValueList += "empty|";//内容为空时添加empty
					}else{
						upValueList += form.items.items[i].getValue()+"|"
					}
				}
			}
			upIdList = upIdList.substring(0, upIdList.length-1);
			upValueList = upValueList.substring(0, upValueList.length-1);
	}
	
	function checkUploadFile(path){//检查上传文件后缀
	    var type = path.substring(path.lastIndexOf(".")+1,path.length);
	    return contains(allowUploadFile, type);
	}

	function contains(arr, obj) {
	    var i = arr.length;  
	    while (i--){
	       if(arr[i]===obj){  
	            return true;
	       }
	    }
	    return false;
	}
	
	function getIsAllCondition(){//上传时获得全局条件
		if(defultData.length>0){
			for(var i=0;i<defultData.length;i++){
				var obj = "new Ext.form.TextField({fieldLabel:\""+defultData[i].name+"\",name:\""+defultData[i].enname+"\",id:\""+defultData[i].enname+"\",emptyText:\"请输入内容\",width:\"300\",labelStyle:\"text-align:right;\"})";
				autoloadcontrol1.add(eval(obj))
				}
			autoloadcontrol1.body.update("");
			autoloadcontrol1.doLayout();
		}
	}
	
 	function getQueryForm(id){//查询前根据选择树节点ID获得相应的自定义查询条件
			$.ajax({
	     	     type:"POST",
	     	     url: link.getformQueryData,
	     	     data:{id:id},
	     	     success:function(data){
	     	    	 if(data[0].name=="err"){
	     	    	 	Ext.getCmp("toppanel").body.update("<form name=\"queryform\" id=\"queryform\" action=\""+link.formQuery+"\" method=\"post\"></form>");
	     	    		data = "";
	     	    		return;
	     	    	 }
	     	    	 setQueryData(data);//设置查询条件
	     	     },
	     	     dataType:"json"
	  	});
	}
	
	 	function setUploadForm(id){//上传前根据选择树节点ID获得相应的自定义查询条件
			$.ajax({
	     	     type:"POST",
	     	     url: link.getformQueryData,
	     	     data:{id:id},
	     	     success:function(data){
	     	    	 if(data[0].name=="err"){
	     	    	 	autoloadcontrol.body.update("无");
	     	    		return;
	     	    	 }
	     	    	setUploadFormData(data);//设置查询条件
	     	     },
	     	     dataType:"json"
	  	});
	}
	
	function setUploadFormData(data){//设置自定义查询条件
		for(var i=0;i<data.length;i++){
			var obj = "new Ext.form.TextField({xtype:\"TextField\",fieldLabel:\""+data[i].name+"\",name:\""+data[i].enname+"\",id:\""+data[i].enname+"\",emptyText:\"请输入内容\",width:\"300\",labelStyle:\"text-align:right;\"})";
			autoloadcontrol.add(eval(obj))
		}
		autoloadcontrol.doLayout(); 
	}
	
	function query(){
		dt();//设置列表表头信息
		getQueryList();//获取查询列表的ID信息
		var valueList = getValueList();//获取查询列表所填写的value
		grids.getStore().removeAll();
		grids.getStore().load({params:{start:0,limit:page_size,table:selectedTableName,types:selectedTypeList,valueList:valueList,idList:idList}});
	}
	
	function reSetForm(){//重置查询信息
		var form=document.getElementById("queryform");
			for(var i=0;i<form.length;i++){
				if (form[i].type == "text"){
					form[i].value="";
				}
			}
	}
	
	//获取表单上填写的自定义查询条件值数组
	function getValueList(){
		var arr=[];
		var form=document.getElementById("queryform");
			for(var i=0;i<form.length;i++){
				if (form[i].type == "text"){
					if(form[i].value!=""){
						arr.push(form[i].value);
					}else{
						arr.push("empty");
					}
				}
			}
		return arr.join("|");
	}
	
	//获取自定义查询条件ID列表数组
	function getQueryList(){
		idList = "";
		var form=document.getElementById("queryform");
		for(var i=0;i<form.length;i++){
			if (form[i].type == "text"){
				idList += form[i].id+"|";
			}
		}
		idList = idList.substring(0, idList.length-1);
	}

	function setQueryData(data){
		htmldata = "<form name=\"queryform\" id=\"queryform\" action=\""+link.formQuery+"\" method=\"post\">"+defultQueryHtml;
			for(var i=0;i<data.length;i++){
				htmldata += "<div class=\"formdiv\"><div class=\"textdiv\">"+data[i].name+":</div><input name=\""+data[i].enname+"\" id=\""+data[i].enname+"\" text=\""+data[i].name+"\" class=\"valuediv\" type=\"text\"/></div>";
			}
			htmldata += "</form>";
			Ext.getCmp("toppanel").body.update(htmldata);
	}
	
	 function getFatherNodeList(node){//查询页面点击树时获得查询需要的selectedTypeList及设置title信息
   		Ext.getCmp("leftpanel").setTitle("文件分类: 所有");
   		var selectedNodeName;
   		selectedTableName = "";
   		if(node.attributes.level=="0"){
   			selectedTableName = node.attributes.tablename;
   			selectedNodeName = node.attributes.text;
   			selectedTypeList = "|"+node.attributes.id+"|";
   		}else if(node.attributes.level=="1"){
   			var fNode = node.parentNode;
   			selectedTableName = fNode.attributes.tablename;
   			selectedNodeName = fNode.text+">"+node.text;
   			selectedTypeList = "|"+fNode.attributes.id+"|"+node.attributes.id+"|";
   		}else if(node.attributes.level=="2"){
   			var fNode = node.parentNode;
   			selectedTableName = fNode.parentNode.attributes.tablename;
   			selectedNodeName = fNode.parentNode.text+">"+fNode.text+">"+node.text;
   			selectedTypeList = "|"+fNode.parentNode.attributes.id+"|"+fNode.attributes.id+"|"+node.attributes.id+"|";
   		}
   		Ext.getCmp("leftpanel").setTitle("文件分类: "+selectedNodeName);
   }
   
      function getUpFatherNodeList(node){//上传页面点击树时获得查询需要的selectedTypeList及设置title信息
   		Ext.getCmp("addWin").setTitle("附件上传");
   		selectedUpTableName = "";
   		var selectedNodeName;
   		if(node.attributes.level=="0"){
   			selectedUpTableName = node.attributes.tablename;
   			selectedNodeName = node.attributes.text;
   			selectedUpTypeList = "|"+node.attributes.id+"|";
   		}else if(node.attributes.level=="1"){
   			var fNode = node.parentNode;
   			selectedUpTableName = fNode.attributes.tablename;
   			selectedNodeName = fNode.text+">"+node.text;
   			selectedUpTypeList = "|"+fNode.attributes.id+"|"+node.attributes.id+"|";
   		}else if(node.attributes.level=="2"){
   			var fNode = node.parentNode;
   			selectedUpTableName = fNode.parentNode.attributes.tablename;
   			selectedNodeName = fNode.parentNode.text+">"+fNode.text+">"+node.text;
   			selectedUpTypeList = "|"+fNode.parentNode.attributes.id+"|"+fNode.attributes.id+"|"+node.attributes.id+"|";
   		}
   		Ext.getCmp("addWin").setTitle("附件上传:"+selectedNodeName);
   }
	
		function tips(value, meta, rec, rowIdx, colIdx, ds){//列表提示
		        var title = "tip:";
	       		meta.attr =  " ext:qtitle = '"+title+"', ext:qtip = '"+value+"'";   
	       	    return value;
		}
		
		var time = {
				id:'time', 
				header: "上传时间", 
				width: 120, 
				sortable: false, 
				dataIndex: 'time',
				renderer:function(value, cellmeta, record, rowIndex, columnIndex, store){
					var time = value.substring(0,value.length-2);
					return time;
					}
				}
				
		var rowIndex;
		var czText ="<a href=\"javascript:;\" onclick=\"javascript:viewFile()\">查看附件</a> <a href=\"javascript:;\" onclick=\"javascript:delFile()\">删除附件</a>";			
		var cz = {
				id:'cz',
				header: "操作",
				width: 90, 
				sortable: false, 
				dataIndex: 'cz',
				renderer:function(value, cellmeta, record, rowIndex, columnIndex, store){
	            var returnStr = czText
	            return returnStr
	          }
		}	
	
	var treeload = new Ext.tree.TreeLoader({  
	              dataUrl : link.getTreeData
	            })
	            
	var mytree=new Ext.tree.TreePanel({
	       animate:true,
	       title:"当前用户:"+user_name,
	       rootVisible:true,
	       autoScroll:true,
	       lines:true,
	       border:false,
	       loader:treeload,
	       root:new Ext.tree.AsyncTreeNode({ 
					id:"root", 
					text:"附件分类", 
					draggable:false, 
					expanded:true 
				}),
		   listeners:{"click":function(node,e){
		   			if(node.attributes.text=="附件分类"){
		   				selectedTableName = "";
		   				selectedTypeList = "";
		   				getDefultData();
		   				Ext.getCmp("leftpanel").setTitle("文件分类: 所有");
		   				return;
		   			}
		   			getFatherNodeList(node);
		   			if(node.attributes.level=="2"){
		   				getQueryForm(node.attributes.id);
		   			}else{
		   				getDefultData();
		   			}
		   		}
		   }
	   });
   
	function init(){//初始化view及获得附件表中的所有字段 并添加到fields
	
 	 	Ext.Ajax.request({
            url: link.getAllDataRead,
            async: false,
            success : function(data) {
                var mynamefield = {};
                var d = eval(data.responseText);
      	     	for(var i=0;i<d.length;i++){
     	     		mynamefield = {name:d[i].name.toLowerCase()}
     	     		fields.push(mynamefield);
     	     	}
     	     	setFields(fields)
            },
            failure : function(request) {
                Ext.MessageBox.show({
                    title : '操作提示',
                    msg : "获取附件表字段失败,请检查!",
                    buttons : Ext.MessageBox.OK,
                    icon : Ext.MessageBox.ERROR
                });
            },
            method : 'get'
        });  
}

function setFields(fields){

		store = new Ext.data.Store({
		autoLoad:false,
		proxy : new Ext.data.HttpProxy({
			 type: "ajax",
			 method: 'POST',
		     url : link.getFileList
		    }),
		reader : new Ext.data.JsonReader({
		fields:fields,
		root : "root",
		totalProperty : "total"
		})
		}); 
	store.on("beforeload",function(){
		store.baseParams={};
});

	var cm = [
	   		new Ext.grid.RowNumberer(),
	   		{id:'id', header: "id", width: 0,hidden:true, sortable: false,hideable:false, dataIndex: 'id',renderer:tips},
	        {id:'filename', header: "附件名称", width: 260, sortable: false, hideable:false,dataIndex: 'filename',renderer:tips},
	        {id:'type', header: "附件类型", width: 50, sortable: false, dataIndex: 'type',renderer:tips},
	        {id:'guid', header: "guid", width: 0,hidden:true,hideable:false, sortable: false, dataIndex: 'guid',renderer:tips},
	        {id:'types', header: "types", width: 0,hidden:true, hideable:false,sortable: false, dataIndex: 'types',renderer:tips},
	        {id:'time', header: "上传时间", width: 120, sortable: false, dataIndex: 'time',
	            renderer:function(value, cellmeta, record, rowIndex, columnIndex, store){
	            var time = value.substring(0,value.length-2)
	            return time;
	          }
	        },
	        {id:'cz', header: "操作", width: 90, sortable: false, dataIndex: 'cz',
	            renderer:function(value, cellmeta, record, rowIndex, columnIndex, store){
	            var returnStr = "<a href=\"javascript:;\" onclick=\"javascript:viewFile()\">查看附件</a> <a href=\"javascript:;\" onclick=\"javascript:delFile()\">删除附件</a>";
	            return returnStr;
	          }}
	        ]
	
	 grids = new Ext.grid.GridPanel({
	    store:store,
	    xtype: "grid",
	    loadMask:true,
	    anchor:"100% 100%",
	    columnLines: true,
	    autoWidth: true,
	    viewConfig: {
		        forceFit: true,
		        border:false,
		        stripeRows: true},
	    sortableColumns:false,
	    bbar : new Ext.PagingToolbar({
		    pageSize : page_size, 
		    store : store, 
		    displayMsg:'当前显示 {0} - {1} 条记录 共 {2} 条记录', 
		    emptyMsg:"无记录",
		    displayInfo : true 
		   }),
	    columns:cm,
	    listeners : {
            beforerender : function(cp) {
            }
        }
	});

	  var toppanel = new Ext.Panel({
        id:"toppanel",
        border: false,
        collapsible: false,
        anchor:"100% 100%",
        html:""
    }); 
	
	  var leftpanel = new Ext.Panel({
	  	title:"选择分类",
        border: false,  
        id:"leftpanel",
        collapsible: false,
        layout:"anchor",
        items:[{
        		border:false,
        		anchor:"100% 25%",
        		autoScroll:true,
        		items:[toppanel],
        		buttonAlign:"right",
        		bbar:[{
                    text: '上传附件材料',
                    iconCls: 'icon-upload',
                    handler:function(){
                    uploadWin();
                    }
                    },'->',{
                    text: '重置',
                    iconCls: 'icon-upload-reset',
                    handler:function(){
                    	reSetForm();
                    }
                    },
        		'->',{
                    text: '查询',
                    iconCls: 'icon-query',
                    handler:function(){
                    	query();
                    }
                    }]
        		},{
        		border:false,
        		id:"gp",
        		layout:"anchor",
        		anchor:"100% 75%",
        		items:[grids]
        		}
        	  ]
    });

		new Ext.Viewport({
	    layout:"border",
	    items: [
                { region: "west", width:200,autoScroll:true, collapsible: false,items:[mytree],layout:"fit",border:true},
                { region: "center", id:'center',width:400,collapsible: false,items:[leftpanel],layout:"fit",border:true }
	    ]
        });
        
        getDefultData();//表单打开时设置默认条件
        grids.getStore().load({params:{start:0,limit:page_size}});
        dt();//设置列表表头信息

}
	
 	function uploadWin(){//上传文件窗口

	var treeload1 = new Ext.tree.TreeLoader({  
              dataUrl : link.getTreeData
            })
            
	var mytree1=new Ext.tree.TreePanel({
	   anchor:"100% 100%",
       animate:true,
       id:"mytree1",
       rootVisible:true,
       autoScroll:true,
       lines:true,
       border:false,
       loader:treeload1,
       root:new Ext.tree.AsyncTreeNode({ 
				id:"root", 
				text:"附件分类", 
				draggable:false, 
				expanded:true 
			}),
	   listeners:{"click":function(node,e){
	   			autoloadcontrol.removeAll();
	   			autoloadcontrol.doLayout(); 
	   			autoloadcontrol.body.update("无");
	   			if(node.attributes.text=="附件分类"){
	   				Ext.getCmp("addWin").setTitle("附件上传");
	   				return;
	   			}else if(node.attributes.level=="2"){
	   				autoloadcontrol.body.update("");
	   				setUploadForm(node.attributes.id);
	   			}
	   			getUpFatherNodeList(node);
	   		}
	   		
	   }
   });
   	  treeload1.on("load",function(node,response){ 
   	  	selectUptree();
   	  })
   	  ;
   
      autoloadcontrol = new Ext.form.FieldSet({
               layout: "form",
               html:"无",
               title: "自定义条件"
           })
           
     autoloadcontrol1 = new Ext.form.FieldSet({
               layout: "form",
               html:"无",
               title: "全局条件"
           })
    autoloadcontrol2 = new Ext.form.FieldSet({
               title: "文件上传",
               items:[{xtype:"fileuploadfield",
	            	labelStyle:"text-align:right",
	                id: "form-file",
	                width:"300",
	                emptyText:"请选择上传的文件",
	                fieldLabel:"文件路径",
	                name:"file",
	                buttonText:"选择文件",
	                buttonCfg:{
	                    iconCls:'icon-selectfile'
	                }}]
           })
 	
		var fp = new Ext.FormPanel({
			id:"fp",
            fileUpload:true,
            autoScroll:true,
            anchor:"100% 100%",
            border:false,
            enctype:"multipart/form-data", 
            bodyStyle:"padding: 10px 10px 0 10px;",  
            labelWidth:"60",
            defaults: {  
                anchor:"95%",
                msgTarget:"side"  
            },
            items:[//autoloadcontrol1,全局条件
	               autoloadcontrol,
	               autoloadcontrol2
                ]

 		})
 		
 	 	var addWin = new Ext.Window({
		    title : "附件上传",
		    id : 'addWin',
		    border : false,
		    width : 730,
		    height : 410,  
		    labelWidth:80,
		    closeAction:'close',
		    plain : true,
		    modal : true,
		    autoScroll:true,
		    buttonAlign:'center',
		    constrain : true,
		    layout:"border",
			items: [{
				    region:"west",
				    autoScroll:true,
				    margins: "5 0 0 0",
				    cmargins: "5 5 0 0",
				    width: "200",
				    minSize: "100",
				    maxSize: "250",
				    layout:"anchor",
				    items:[mytree1]
				},{
				    collapsible: false,
				    region:"center",
				    margins: "5 0 0 0",
				    autoScroll:true,
				    items:[fp]
				}],
			buttons: [{  
                    text: "上传",  
                    iconCls:"icon-uploadfile",
                    handler: function(){
                    	if(Ext.getCmp("form-file").getValue().trim()==""){
                    		alert("请选择需要上传的文件");
                    		return;
                    	}
                        if (fp.getForm().isValid()){
                            var allow = checkUploadFile(Ext.getCmp("form-file").getValue());
                            if(!allow){
                        	alert("无法上传此文件类型的文件");
                        	return;
                        	}
                        if(selectedUpTableName==""){
                        	alert("请选择文件分类");
                        	return;
                        }
                        	setUpData();//获取上传时填写的内容
                          fp.getForm().submit({
                                url:link.uploadFile+"?maxSize="+maxSize+"&upIdList="+upIdList+"&upValueList="+upValueList+"&types="+selectedUpTypeList+"&table="+selectedUpTableName,
                                waitTitle:"请稍候",
                                waitMsg:"正在上传...",
                                success:function(fp,o){
                                	if(o.result.message=="success"){
                                		Ext.Msg.alert("提示消息","上传成功"); 
                                	}else if(o.result.message=="error001"){
                                		Ext.Msg.alert("错误","数据库插入数据失败");
                                	}else if(o.result.message=="error002"||o.result.message=="error003"){
                                		Ext.Msg.alert("错误","文件上传失败"); 
                                	}else if(o.result.message=="error004"){
                                		Ext.Msg.alert("错误","文件大小超出"); 
                                	}
                                }
                            }); 
                        }  
                    }  
                },{  
                    text: '重置',  
                    iconCls:'icon-upload-reset',
                    handler:function(){
                        fp.getForm().reset();
                    }  
					}] 
		});
 		addWin.show();
 		//getIsAllCondition();//打开上传界面时获得全局条件
 	}
 	
		init();//初始化表单
		getDefultData();
});
package com.fm.action;
import java.sql.*;
import org.apache.struts2.ServletActionContext;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;
  
import org.apache.commons.fileupload.DiskFileUpload;  
import org.apache.commons.fileupload.FileItem;
import com.fm.dao.FileManagerDao;
import com.fm.entity.FileTypeEntity;
import com.fm.tool.Tool;



public class FileUploadAction extends ActionSupport {
    private File file;
    private String fileFileName;
    private String fileContentType;
    private Boolean success = true;

	GuidAction GuidAction = new GuidAction();
	FileManagerDao dao = new FileManagerDao();
	Tool tool = new Tool();
    
	HttpServletRequest request=ServletActionContext.getRequest();
	HttpServletResponse response=ServletActionContext.getResponse();


    public void upload() throws IOException{
    	String table = request.getParameter("table");
    	String s_maxSize = request.getParameter("maxSize");
    	String types = request.getParameter("types");
    	String upIdList = request.getParameter("upIdList");
    	String upValueList = request.getParameter("upValueList");
		String[] idArr = null;
		String[] valueArr = null;
		if(upIdList!=null){idArr = upIdList.split("\\|");}
		if(upValueList!=null){valueArr = upValueList.split("\\|");}
		String sql1 = "";
		String sql2 = "";
		if(idArr.length>0&&idArr!=null){
			for(int i=0;i<idArr.length;i++){
				sql1 += ","+idArr[i];
				if(valueArr[i]!=null&&!valueArr[i].equals("empty")){
					sql2 += ",'"+valueArr[i]+"'";
				}else{
					sql2 += ",''";
				}
			}
			if(sql1.equals(",")){sql1="";}
			if(sql2.equals(",''")){sql2="";}
		}
    	boolean state = true;
    	String message = "success";
    	long maxSize = Long.parseLong(s_maxSize);
    	 	if(!(maxSize<getFile().length())){//文件大小不超过设置最大值
    	 		String savePath = ServletActionContext.getServletContext().getRealPath("/AffixFiles/FileManager/");
    	        String guid = GuidAction.GenerateGUID().replaceAll("-","");//获得GUID
    	        String fileName = getFileFileName().substring(0,getFileFileName().lastIndexOf("."));//获得文件名称
    	        String fileType = getFileFileName().substring(getFileFileName().lastIndexOf(".")+1,getFileFileName().length()).toUpperCase();//获得文件后缀
    	        String fullFileName = guid + "." + fileType;//获得文件名 GUID+后缀名
    	        String filePath = savePath + "\\" + fullFileName;//获得文件完整路径
    	        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
    	        String uploadDate = df.format(new Date());//获得当前日期
    	        String sql = "insert into FILE_MANAGER( filename , type , guid , filepath , types , time) values ('"+fileName+"','"+fileType+"','"+guid+"','"+filePath+"','"+types+"',to_date('"+uploadDate+"','yyyy-mm-dd hh24:mi:ss'))";
    	        System.out.println(sql);
    	        boolean sqlFlag = Tool.execSql(sql);
    		        if(!sqlFlag){//SQL语句执行错误时
    		        	state = false;
    		        	message = "error001";//数据库插入数据失败
    		        	}else{
    		        		sql = "insert into "+table+"(guid"+sql1+") values ('"+guid+"'"+sql2+")";
    		        		boolean sqlFlag1 = Tool.execSql(sql);
    		        		if(sqlFlag1){
    		        	    	boolean fileFlag = uploadFile(savePath,fullFileName);
        		        		if(!fileFlag){//文件上传出错时
        		        			state = false;
        		        			message = "error002";//文件上传失败
        		        			sql = "delete from FILE_MANAGER where guid = " + guid;
        		        			sql2 = "delete from "+table+" where guid = " + guid;
        		        			boolean delFlag = Tool.execSql(sql);//删除插入的数据
        		        			boolean delFlag2 = Tool.execSql(sql);//删除插入的数据
        		        				if(!delFlag||!delFlag2){message = "error003";}//删除失败
        		        		}
    		        		}else{//插入自定义表失败
    		        			message = "error001";//数据库插入数据失败
    		        		}
    		        	}
    	 	}else{
    	 		message = "error004";//文件大小超过最大值
    	 	}
	        String result = "{\"success\":\""+state+"\",\"message\":\""+message+"\"}";
		    tool.writerJson(response, result);
    }
    
    private boolean uploadFile(String path,String fullFileName){
    	File pathDir = new File(path);
    	if (!pathDir.exists()){pathDir.mkdirs();}//默认保存文件夹路径不存在时建立文件夹
    	FileOutputStream fos = null;
        FileInputStream fis = null;
        try {
            // 建立文件输出流
            fos = new FileOutputStream(path + "\\" + fullFileName);
            // 建立文件上传流
            fis = new FileInputStream(getFile());
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = fis.read(buffer)) > 0) {
                fos.write(buffer, 0, len);
            }
        } catch (Exception e) {
            System.out.println("文件上传失败");
            //e.printStackTrace();
            return false;
        } finally {
            close(fos, fis);
        }
    	return true;
    }

    
 /*   private boolean uploadFile(String path,String fullFileName){
    	File pathDir = new File(path);
    	if (!pathDir.exists()){pathDir.mkdirs();}//默认保存文件夹路径不存在时建立文件夹
    	FileOutputStream fos = null;
        FileInputStream fis = null;
        try {
            // 建立文件输出流
            fos = new FileOutputStream(path + "\\" + fullFileName);
            // 建立文件上传流
            fis = new FileInputStream(getFile());
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = fis.read(buffer)) > 0) {
                fos.write(buffer, 0, len);
            }
        } catch (Exception e) {
            System.out.println("文件上传失败");
            //e.printStackTrace();
            return false;
        } finally {
            close(fos, fis);
        }
    	return true;
    }*/
    
    

    private void close(FileOutputStream fos, FileInputStream fis) {
        if (fis != null) {
            try {
                fis.close();
            } catch (IOException e) {
                System.out.println("FileInputStream关闭失败");
                e.printStackTrace();
            }
        }
        if (fos != null) {
            try {
                fos.close();
            } catch (IOException e) {
                System.out.println("FileOutputStream关闭失败");
                e.printStackTrace();
            }
        }
    }
    
    
    
    
    
    
    public File getFile() {
		return file;
	}

	public void setFile(File file) {
		this.file = file;
	}
    
	public String getFileFileName() {
		return fileFileName;
	}

	public void setFileFileName(String fileFileName) {
		this.fileFileName = fileFileName;
	}

	public String getFileContentType() {
		return fileContentType;
	}

	public void setFileContentType(String fileContentType) {
		this.fileContentType = fileContentType;
	}
	
    public Boolean getSuccess() {
		return success;
	}

	public void setSuccess(Boolean success) {
		this.success = success;
	}
  
}


struts2文件上传例子

标签:

原文地址:http://blog.csdn.net/wyqhl/article/details/51314027

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!