Flex中实现的文件上传主要用到以下两个类:
●FileReference:FileReference 类提供了在用户计算机和服务器之间上载和下载文件的方法。操作系统对话框会提示用户选择要上载的文件或用于下载的位置。每个 FileReference 对象都引用用户磁盘上的一个文件并且具有一些属性,这些属性包含有关文件大小(size)、类型(type)、名称(name)、创建日期(creationDate)、修改日期(modificationDate)和创建者类型(仅限Macintosh)的信息。
●FileReferenceList 类提供了让用户选择一个或多个要上载的文件的方法。FileReferenceList 对象将用户磁盘上的一组本地文件(一个或多个文件)表示为 FileReference 对象的数组。有关详细信息以及有关 FileReference 对象和 FileReference 类(可与 FileReferenceList 一起使用)的重要注意事项,请参阅 FileReference 类。
FileReferenceList 类的使用方法为:
① 将该类实例化:var myFileRef = new FileReferenceList();
② 调用FileReferenceList.browse() 方法,该方法将打开一个对话框,让用户选择一个或多个要上载的文件:myFileRef.browse();
③ 在成功调用browse() 方法之后,使用 FileReference 对象数组来填充 FileReferenceList 对象的fileList 属性。
④ 对fileList 数组中的每个元素调用FileReference.upload()。
好了,现在开始实现文件上传,首先新建一个Application文件UploadFileDemo.mxml,代码如下所示:
<?xmlversion="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)"> <fx:Script> <![CDATA[ import ases.FileReferenceVo; 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 varselectFileList:FileReferenceList=new FileReferenceList(); //存贮选择文件的数组 [Bindable] public var fileArrayCollction:ArrayCollection=newArrayCollection(); //此数组用于保存文件信息 [Bindable] public var arrayCollection:ArrayCollection=newArrayCollection(); //此数组用于DataGrid表格中显示 public varurlRequest:URLRequest=new URLRequest("http://localhost:9080/javaAndFlex/FileUploadServlet"); //服务器类地址 protected function application_initializeHandler(event:FlexEvent):void { // TODOAuto-generated method stub selectFileList.addEventListener(Event.SELECT,selectFileHandler); //选择文件监听器 } public function selectFiles():void{ //浏览文件处理事件 //arrayCollection.removeAll(); var imagesFilter:FileFilter = new FileFilter("Images", "*.jpg;*.gif;*.png"); //选择的图片类型 var docFilter:FileFilter = new FileFilter("Documents", "*.pdf;*.doc;*.txt"); //选择的文档类型 var videoFilter:FileFilter= new FileFilter("Videos"," *.mp3;*.mp4;*.avi;*.rmvb"); //选择的视频类型 selectFileList.browse([imagesFilter,docFilter,videoFilter]); } public function selectFileHandler(event:Event):void{ //处理选择文件 for(var i:int=0;i<selectFileList.fileList.length;i++){ varfileReference: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; } for(var i:int=0;i<fileArrayCollction.length;i++){ varfileReference: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(); } } ]]> </fx:Script> <fx:Declarations> <!-- Place non-visualelements (e.g., services, value objects) here --> </fx:Declarations> <s:Panel x="304" y="131" width="717" height="380" title="文件上传" fontSize="18"> <mx:DataGrid x="25" y="14" id="fileDataGrid" fontWeight="bold" width="669" fontSize="16"height="261" > <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[ importmx.collections.ArrayCollection; protected functiondeleteFile_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 functionprogressBar_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('images/delete.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="218" y="295" width="100%" height="100%"> <s:Button id="browseFile" height="31" label="浏览..." fontSize="18" click="selectFiles()"/> <s:Button id="uploadFile" height="31" label="上传" fontSize="18"click="uploadFile_clickHandler(event)"/> <s:Button id="cancleUpload" height="31" label="清空" fontSize="18"click="cancleUpload_clickHandler(event)"/> </mx:HBox> </s:Panel> </s:Application>
运行时页面如下所示:
新建一个servlet类FileUploadServlet,代码如下所示:
package com.ldfsoft.servlet; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.util.Iterator; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; importjavax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; importorg.apache.commons.fileupload.FileItem; importorg.apache.commons.fileupload.FileUploadException; importorg.apache.commons.fileupload.disk.DiskFileItemFactory; importorg.apache.commons.fileupload.servlet.ServletFileUpload; public class FileUploadServlet extendsHttpServlet { @SuppressWarnings("unchecked") @Override protected void service(HttpServletRequestrequest, HttpServletResponse response) throwsServletException, IOException { //TODO Auto-generated method stub response.setContentType("text/html;charset=utf-8"); DiskFileItemFactory diskFileItemFactory=newDiskFileItemFactory(); ServletFileUpload servletFileUpload=newServletFileUpload(diskFileItemFactory); servletFileUpload.setHeaderEncoding("utf-8"); servletFileUpload.setSizeMax(1024*1024*1024); try { List<FileItem>items=servletFileUpload.parseRequest(request); Iterator<FileItem>iterator=items.iterator(); while(iterator.hasNext()){ FileItemitem=(FileItem) iterator.next(); if(!item.isFormField()){ StringfileName=item.getName(); Stringpath=getServletContext().getRealPath("/")+"files/"; //文件上传目录为根目录下面的files文件夹里 System.out.println(fileName); FileuploadFile=new File(path+fileName); item.write(uploadFile); } } }catch (FileUploadException e) { //TODO Auto-generated catch block e.printStackTrace(); }catch (Exception e) { //TODO Auto-generated catch block e.printStackTrace(); } } }
注意,这个servlet文件需要两个jar包:commons-fileupload-1.2.1.jar和commons-io-1.3.2.jar,我这两个jar包是用Struts2.2.1.1版本里面的。
开始选择文件:
点击上传按钮后,文件开始上传,由于本地上传速度那是相当的快,所以小文件只是片刻之间的事。上传中“浏览”按钮,“上传”按钮,“清空”按钮都置灰,而且进度条后的删除按钮也都不可见,效果如下所示:
上传完毕后这3个按钮恢复正常并且会提示你是否继续上传,如下所示:
好了,演示完毕,这就是这两天的劳动的成果,觉得好就支持我一下吧,第一次做这个还是蛮幸苦的。下节决定做文件下载,尽情期待…
原创文章,转载请注明出处:http://www.dianfusoft.com/