jsp利用flex实现多文件选择上传demo

由于项目需要,要在页面选中多个文件后上传,大家都知道普通的html标签file并不能支持文件多选,只好找些资料,使用flex能够做到这点。以下是上传所用的mxml代码,当然里面的处理路径各不相同,由自己确定。当然最好是自己弄个flexbuilder,自己根据需求调整页面。

<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
			   xmlns:s="library://ns.adobe.com/flex/spark"
			   xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600" applicationComplete="application_initializeHandler(event)" initialize="init()">
	<fx:Script>
		<![CDATA[
			import flash.net.navigateToURL;
			
			import flashx.textLayout.events.SelectionEvent;
			
			import mx.collections.ArrayCollection;
			import mx.controls.Alert;
			import mx.events.CloseEvent;
			import mx.events.FlexEvent;
			import mx.rpc.events.FaultEvent;
			
			import spark.primitives.supportClasses.FilledElement;
			
			public var selectFileList:FileReferenceList = new FileReferenceList(); //存贮选择文件的数组
			[Bindable]
			public var fileArrayCollction:ArrayCollection=new ArrayCollection();   //此数组用于保存文件信息
			[Bindable]
			public var arrayCollection:ArrayCollection=new ArrayCollection();  //此数组用于DataGrid表格中显示
			
			protected function application_initializeHandler(event:FlexEvent):void
			{
				// TODOAuto-generated method stub
				selectFileList.addEventListener(Event.SELECT,selectFileHandler);  //选择文件监听器
			}
			public function selectFiles():void{  //浏览文件处理事件
				//arrayCollection.removeAll();
				selectFileList.browse([new FileFilter("excel (*.xls)", "*.xls"),
					new FileFilter("所有文件(*.*)", "*.*")
				]);
			}
			public function selectFileHandler(event:Event):void{  //处理选择文件
				for(var i:int=0;i<selectFileList.fileList.length;i++){
					var fileReference:FileReference=FileReference(selectFileList.fileList[i]);
					var object:Object=new Object();
					object.fileRefer=fileReference;
					object.fileName=fileReference.name;
					object.fileType=fileReference.type.substr(1);
					object.fileSize=(fileReference.size/1024).toFixed(2)+"KB";
					fileArrayCollction.addItem(object);
					arrayCollection.addItem(object);
				}
				fileDataGrid.dataProvider=arrayCollection;
			}
			
			protected function cancleUpload_clickHandler(event:MouseEvent):void  //清空按钮处理函数
			{
				// TODOAuto-generated method stub
				Alert.yesLabel="是的";
				Alert.cancelLabel="取消"
				if(fileArrayCollction.length<1){
					Alert.show("没有要上传的文件!","提示");
					return;
				}
				
				Alert.show("确实要清空文件上传列表吗?","提示",Alert.YES|Alert.CANCEL,this,yesOrCancleHandler,null,Alert.CANCEL);
				
				
			}
			public function yesOrCancleHandler(event:CloseEvent):void{
				if(event.detail==Alert.YES){
					arrayCollection.removeAll();
					fileArrayCollction.removeAll();
					fileDataGrid.dataProvider=arrayCollection;
					
				}
			}
			
			protected function uploadFile_clickHandler(event:MouseEvent):void  //文件上传处理函数
			{
				// TODOAuto-generated method stub
				if(fileArrayCollction.length<1){
					Alert.show("请选择要上传的文件!","提示");
					return;
				}
				var urlRequest:URLRequest=new URLRequest(currSwfUrl+"/fileupload/upload.jsp");  //服务器类地址 
				for(var i:int=0;i<fileArrayCollction.length;i++){
					var fileReference:FileReference=FileReference(fileArrayCollction[i]['fileRefer']);
					
					//fileUpLoad.upload(fileReference.data,fileReference.name);
					fileReference.upload(urlRequest);
					browseFile.enabled=false;  //将浏览文件按钮置灰
					uploadFile.enabled=false;  //将上传按钮置灰
					cancleUpload.enabled=false;  //将清空按钮置灰
					if(i==fileArrayCollction.length-1){
						fileReference.addEventListener(Event.COMPLETE,fileUploadCompleteHandler);
					}
				}
			}
			protected function fileUploadCompleteHandler(event:Event):void{
				browseFile.enabled=true;
				uploadFile.enabled=true;
				cancleUpload.enabled=true;
				Alert.yesLabel="是";
				Alert.cancelLabel="否";
				Alert.show("文件已经上传完毕,是否接着上传?","提示",Alert.YES|Alert.CANCEL,this,chooseUploadFile,null,Alert.CANCEL);
			}
			protected function chooseUploadFile(event:CloseEvent):void{  //上传文件完毕后的处理函数
				if(event.detail==Alert.YES){
					this.selectFiles();
				}
				if(event.detail == Alert.CANCEL){
					beginToImport();
				}				
			}
			
			private function beginToImport():String{
				Alert.show("正在导入,请等待...","温馨提示");
				var result:String = "false";
				var url:String = currSwfUrl +"/oa/canjirenbaseinfosave.do";
				ExternalInterface.call("function(){window.location.href ='"+currSwfUrl+"/fileupload/uploadcomplete.jsp';}");
				//1.varurl:String="http://localhost:8080/Flex_J2eeDemo/bin/Welcome.html";  2.varrequest:URLRequest=newURLRequest(url);  3.navigateToURL(request,"_blank"); 
				//ExternalInterface.call("function()  2.{window.location.href='http://localhost:8080/Flex_J2eeDemo/bin/Welcome.html';}  3. 4.");
				return result;
			}
			
			public var currSwfUrl:String;  //在Application中声明的当前swf的路径
			
			private function init():void
			{ 
				var swfPath:String = this.parent.stage.loaderInfo.url;//获取当前swf的路径
				var swfPathArray:Array = swfPath.split("/");  
				
				if (swfPathArray[0] == "file:") {  //本地路径
					if(swfPathArray.length<=3){  
						
						currSwfUrl = swfPathArray[2];  
						currSwfUrl = currSwfUrl.substring(0,currSwfUrl.lastIndexOf(currSwfUrl.charAt(2)));  
					}
					else{  
						currSwfUrl = swfPath;  
						currSwfUrl = currSwfUrl.substring(0,currSwfUrl.lastIndexOf("/"));  
					}  
				}else{  //网络路径
					currSwfUrl = swfPath;  
					currSwfUrl = currSwfUrl.substring(0,currSwfUrl.lastIndexOf("/"));  
				}  
				
				currSwfUrl = currSwfUrl.substr(0,currSwfUrl.lastIndexOf("/"));
			}

		]]>
	</fx:Script>
	<fx:Declarations>
		<!-- Place non-visualelements (e.g., services, value objects) here -->
	</fx:Declarations>
	<s:Panel x="0" y="0" width="100%" height="100%" title="文件上传(选择需要同步的excel数据进行上传,完成后将自动同步到数据库)" fontSize="18">
		<mx:DataGrid  x="67" y="10" id="fileDataGrid"  fontWeight="bold" width="90%" fontSize="16" height="300" >
				<mx:columns>
					<mx:DataGridColumn headerText="文件名" width="200" dataField="fileName" />
					<mx:DataGridColumn headerText="文件大小" width="100" dataField="fileSize" />
					<mx:DataGridColumn headerText="文件类型" width="100" dataField="fileType" />
					<mx:DataGridColumn headerText="上传进度"  >
						<mx:itemRenderer>
							<fx:Component>
								<mx:HBox width="100%" height="100%" paddingLeft="10" >
									<fx:Script>
										<![CDATA[ 
											import mx.collections.ArrayCollection;
											
											protected function deleteFile_clickHandler(event:MouseEvent):void
											{
												// TODO Auto-generated method stub
												//
												var grid:Object =event.target.parent.parent.parent;
												var dp:ArrayCollection =ArrayCollection(grid.dataProvider);
												var index:int = dp.getItemIndex(data);
												outerDocument.arrayCollection.removeItemAt(index);
												dp.removeItemAt(index);
												grid.parent.refresh();
											}
											
											protected function progressBar_progressHandler(event:ProgressEvent):void
											{
												// TODO Auto-generated method stub
												deleteFile.visible=false;
											}
											
											protected function progressBar_completeHandler(event:Event):void
											{
												// TODO Auto-generated method stub
												deleteFile.visible=true;
											}
											
											
											
										]]>
									</fx:Script>
									<mx:ProgressBar minimum="0" chromeColor="13892729" maximum="100" progress="progressBar_progressHandler(event)" complete="progressBar_completeHandler(event)"     labelPlacement="center"  source="{data.fileRefer}" label="%3%%" id="progressBar"   width="90%" />
									<mx:LinkButton id="deleteFile" width="10%" icon="@Embed('del1.png')" click="deleteFile_clickHandler(event)" />
								</mx:HBox >
							</fx:Component>
						</mx:itemRenderer>
					</mx:DataGridColumn>
				</mx:columns>
			</mx:DataGrid>
		<mx:HBox paddingLeft="20" horizontalGap="35" paddingTop="8" x="161" y="335" width="1093" height="64">
			<s:Button id="browseFile" height="31" label="浏览..." fontSize="18" click="selectFiles()"/>
			<s:Button id="uploadFile" height="31" label="同步" click="uploadFile_clickHandler(event)"
					  fontSize="18"/>
			<s:Button id="cancleUpload" height="31" label="清空" fontSize="18" click="cancleUpload_clickHandler(event)"/>
		</mx:HBox>
	</s:Panel>
</s:Application>

 2.文件上传处理的jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@page import="java.io.File"%>
<%@page import="org.apache.commons.fileupload.disk.DiskFileItemFactory"%>
<%@page import="org.apache.commons.fileupload.servlet.ServletFileUpload"%>
<%@page import="org.apache.commons.fileupload.FileItem"%>
<%@page import="org.apache.commons.fileupload.FileUploadException"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
// 定义文件的上传路径 
String uploadPath = "";
uploadPath = request.getRealPath("/");
uploadPath += "excelfiles"+File.separator+"20130204"+File.separator;
File file = new File(uploadPath);
if(!file.exists()){
	file.mkdir();
}
System.out.println("file path is "+file.getPath());
request.setAttribute("ENCTYPE", "multipart/form-data");
response.setContentType("text/html;charset=UTF-8"); 
//保存文件到服务器中 
DiskFileItemFactory factory = new DiskFileItemFactory(); 
factory.setSizeThreshold(4096); 
ServletFileUpload upload = new ServletFileUpload(factory); 
upload.setHeaderEncoding("utf-8");
upload.setSizeMax(1024*1000); 
try { 
   List fileItems = upload.parseRequest(request); 
   Iterator iter = fileItems.iterator(); 
   while (iter.hasNext()) { 
       FileItem item = (FileItem) iter.next(); 
       if (!item.isFormField()) { 
           String name = item.getName();
           try { 
               item.write(new File(uploadPath + name)); 
               response.getWriter().write("success");
           } catch (Exception e) { 
               e.printStackTrace(); 
               response.getWriter().write(e.getMessage());
           } 
       } 
   }
   System.out.println("上传文件成功.......");
} catch (FileUploadException e) { 
   e.printStackTrace(); 
   response.getWriter().write(e.getMessage());
   System.out.println(e.getMessage() + "结束"); 
} 

%>

  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值