我这里的需求是上传前可以删除不需要的,开始上传后不可以更改。
uploadgrid.mxm 上传jar的类,
<?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" creationComplete="group_creationCompleteHandler(event)" xmlns:mx="library://ns.adobe.com/flex/mx" width="500" height="250"> <s:layout> <s:BasicLayout/> </s:layout> <fx:Declarations> <mx:NumberFormatter id="filesizeFormatter" useThousandsSeparator="true"/> </fx:Declarations> <fx:Script> <![CDATA[ import mx.collections.ArrayCollection; import mx.controls.Alert; import mx.events.CloseEvent; import mx.events.CollectionEvent; import mx.events.FlexEvent; import mx.formatters.CurrencyFormatter; import mx.formatters.NumberFormatter; [Bindable] public var deleteenabled:Boolean=true; //文件列表 [Bindable] private var fileRefs: FileReferenceList = new FileReferenceList(); //这个地址是我测试用的服务器地址 [Bindable] private var urlrequest: URLRequest = new URLRequest("http://localhost:8080/auto/FileUploaded"); //文件列表中的文件 [Bindable] public var selectedFiles: ArrayCollection = new ArrayCollection([]); //上传的文件 private var singleThreadFiles: Array = []; //逐个上传文件 private function singleThreadUploadFile(): void { //FIFO:逐个从列表中取出,进行上传 if (singleThreadFiles.length > 0) { var mf: MyFile = singleThreadFiles.pop() as MyFile ; var f:FileReference=mf.fr; f.addEventListener(DataEvent.UPLOAD_COMPLETE_DATA, doSingleUploadFileComplete); f.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler); f.upload(urlrequest); } else { uploadbutton.enabled=false; uploadtext.text="全部上传成功!"; showuploadjar(); } } private function doSingleUploadFileComplete(event: Event): void { var uploadInfo:String=event.data; var uploadInfoArray:Array = uploadInfo.split("#"); if(uploadInfoArray[0]=="true") { var f: FileReference = event.target as FileReference; f.removeEventListener(Event.COMPLETE, doSingleUploadFileComplete); singleThreadUploadFile(); }else { Alert.show(uploadInfoArray[1]+"请检查网络或程序是否正常,目录是否正确并创建,请删除上传不成功的jar,重新选择后上传!"); selectFileButton.enabled=true; cleanAll.enabled=true; deleteenabled=true; } } //初始化 private function init(): void { Security.allowDomain("*"); fileRefs.addEventListener(Event.SELECT, fileSelectHandler); fileRefs.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler); addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler); } //要上传的文件类型,我这里是jar文件 private function selectFile(): void { var jarfile:FileFilter = new FileFilter("jar文件(*.jar)", "*.jar*"); var allfile:FileFilter = new FileFilter("所有文件(*.*)", "*.*"); var allTypes:Array = new Array(); allTypes.push(jarfile); allTypes.push(allfile); fileRefs.browse(allTypes); } //用户选择的文件,如果需要判断是否可以多次选择同名的文件可以在这里判断 private function fileSelectHandler(event: Event): void { for each (var f: FileReference in fileRefs.fileList) { var mf:MyFile = new MyFile(f); selectedFiles.addItem(mf); } } //出错后的处理 private function ioErrorHandler(e:IOErrorEvent): void { Alert.show(e.text); Alert.show("请检查网络或程序是否正常,请删除上传不成功的jar,重新选择后上传!"); selectFileButton.enabled=true; cleanAll.enabled=true; deleteenabled=true; } //删除列表中的文件 public function removeFile(mf: MyFile): void { var index: int = selectedFiles.getItemIndex(mf); if (index != -1) selectedFiles.removeItemAt(index); } //初始化组件或应用程序 protected function group_creationCompleteHandler(event:FlexEvent):void { init(); } //确认上传的文件 protected function button1_clickHandler(event:MouseEvent):void { Alert.show("开始上传后不能更改选择的jar包 ,确定上传?", "确认上传", Alert.YES|Alert.NO, null, startUpload); } //根据业务的需求上传后不能更改,可以根据自己的业务逻辑去改相应的处理 private function startUpload(e: CloseEvent): void{ if (e.detail == Alert.YES){ selectFileButton.enabled=false; cleanAll.enabled=false; deleteenabled=false; singleThreadFiles = selectedFiles.toArray().concat(); for(var i:int=0;i<singleThreadFiles.length;i++) { if(singleThreadFiles[i] is MyFile) { var mf:MyFile= singleThreadFiles[i] as MyFile; var f:FileReference=mf.fr; trace(f.name); } } singleThreadFiles.reverse(); singleThreadUploadFile(); } } //输出上传后的jar的信息,如果需要更多的信息可以在MyFlie类里找到 private function showuploadjar():void { for(var i:int=0; i<selectedFiles.length;i++) { var mf:MyFile=selectedFiles.getItemAt(i) as MyFile; // Alert.show(mf.uploadFilePath+mf.uploadFileName); trace("上传后的路径:"+mf.uploadFilePath+mf.uploadFileName); mf.removeDateEvent(); } } ]]> </fx:Script> <s:VGroup paddingTop="10"> <mx:VBox> <mx:HBox width="100%"> <mx:Button id="selectFileButton" label="浏览" click="selectFile()"/> <mx:Box width="100%" horizontalAlign="right"> <mx:Button id="cleanAll" click="selectedFiles.removeAll();" label="清空"/> </mx:Box> </mx:HBox> <mx:DataGrid id="files" dataProvider="{selectedFiles}" > <mx:columns> <mx:DataGridColumn width="200" headerText="文件名" dataField="fr.name" /> <mx:DataGridColumn width="100" headerText="大小(字节)" dataField="fr.size"> <mx:itemRenderer> <fx:Component> <mx:Label text="{outerDocument.filesizeFormatter.format(data.size)}" textAlign="right"/> </fx:Component> </mx:itemRenderer> </mx:DataGridColumn> <mx:DataGridColumn width="100" headerText="状态" dataField="uploadlable" /> <mx:DataGridColumn headerText="删除" width="80"> <mx:itemRenderer> <fx:Component> <mx:HBox fontSize="10" fontWeight="normal" fontThickness="1"> <fx:Script> <![CDATA[ protected function linkbutton1_clickHandler(event:MouseEvent):void { var mf:MyFile = data as MyFile; outerDocument.removeFile(mf); } ]]> </fx:Script> <mx:LinkButton label="Delete" click="linkbutton1_clickHandler(event)" enabled="{outerDocument.deleteenabled}"> </mx:LinkButton> </mx:HBox> </fx:Component> </mx:itemRenderer> </mx:DataGridColumn> </mx:columns> </mx:DataGrid> <mx:HBox> <mx:Button label="上传" id="uploadbutton" click="button1_clickHandler(event)" /> <s:Label paddingTop="7" id="uploadtext" text="" /> </mx:HBox> </mx:VBox> </s:VGroup> </s:Application>
自己封装as类MyFile.as:用于存储上传后的信息。
package outsideSys.windows { import flash.events.DataEvent; import flash.events.Event; import flash.events.ProgressEvent; import flash.net.FileReference; /** * @author * 描述: * 创建时间:2012-12-4 下午2:01:56 */ [Bindable] public class MyFile { private var _uploadFileName:String; private var _uploadFilePath:String; private var _uploadIsSuceess:Boolean; private var _uploadProgress:uint; private var _uploadlable:String="等待上传"; private var _fr:FileReference; public function MyFile(f:FileReference) { super(); this.fr=f; _fr.addEventListener(DataEvent.UPLOAD_COMPLETE_DATA,uploadcomplete); // _fr.addEventListener(ProgressEvent.PROGRESS,funcuploadProgress); } public function removeDateEvent():void { _fr.removeEventListener(DataEvent.UPLOAD_COMPLETE_DATA,uploadcomplete); } protected function uploadcomplete(event: DataEvent): void { //服务器端一定要返回数据,否则,这个方法就不起作用了 var uploadInfo:String=event.data; var uploadInfoArray:Array = uploadInfo.split("#"); if(uploadInfoArray[0]=="true") { this.uploadIsSuceess=true; this.uploadFilePath=uploadInfoArray[1]; this.uploadFileName=uploadInfoArray[2]; this.uploadlable=uploadInfoArray[3]; //trace(uploadlable); trace(uploadFileName+"完成2"); } } // protected function funcuploadProgress(event: ProgressEvent): void // { // this.uploadProgress = event.bytesLoaded / event.bytesTotal * 100; // } public function get uploadlable():String { return _uploadlable; } public function set uploadlable(value:String):void { _uploadlable = value; } public function get fr():FileReference { return _fr; } public function set fr(value:FileReference):void { _fr = value; } public function get uploadProgress():uint { return _uploadProgress; } public function set uploadProgress(value:uint):void { _uploadProgress = value; } public function get uploadIsSuceess():Boolean { return _uploadIsSuceess; } public function set uploadIsSuceess(value:Boolean):void { _uploadIsSuceess = value; } public function get uploadFilePath():String { return _uploadFilePath; } public function set uploadFilePath(value:String):void { _uploadFilePath = value; } public function get uploadFileName():String { return _uploadFileName; } public function set uploadFileName(value:String):void { _uploadFileName = value; } } }
后台的java代码FileUploaded.java:
package com.web.action; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Iterator; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; 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 com.system.constants.PropertiesFile; import com.system.util.PropertiesAnalysis; //import com.system.constants.PropertiesFile; //import com.system.util.PropertiesAnalysis; /** * * @author crystal */ public class FileUploaded extends HttpServlet { /** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods. * @param request servlet request * @param response servlet response */ // 定义文件的上传路径 // private String uploadPath = PropertiesAnalysis.findProperties(PropertiesFile.DEPLOYXONFIG, "jarpath"); private String uploadPath = "D://jarfile//"; // 限制文件的上传大小 private int maxPostSize = 100 * 1024 * 1024; public FileUploaded() { super(); } public void destroy() { super.destroy(); } protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("Access !"); response.setContentType("text/html;charset=UTF-8"); request.setCharacterEncoding("UTF-8"); PrintWriter out = response.getWriter(); //保存文件到服务器中 DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(4096); ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(maxPostSize); try { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); String date=sdf.format(new Date()); String jaruploadPath=uploadPath+date+"\\"; File file = new File(jaruploadPath); //判断文件夹是否存在,如果不存在则创建文件夹 if (!file.exists()) { file.mkdir(); } List fileItems = upload.parseRequest(request); Iterator iter = fileItems.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (!item.isFormField()) { String name = item.getName(); System.out.println(name); String newname=name.split(".jar")[0]+new Date().getTime()+".jar"; try { item.write(new File(jaruploadPath + newname)); //我输出的格式:true|flase#文件路径#文件名#是否成功的信息,用#号隔开的。 response.getWriter().write("true#"+jaruploadPath+"#"+newname+"#上传成功。"); } catch (Exception e) { e.printStackTrace(); response.getWriter().write("false#"+e.getMessage()); } } } } catch (FileUploadException e) { e.printStackTrace(); response.getWriter().write(e.getMessage()); System.out.println("false#"+e.getMessage() + "结束"); } } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP <code>GET</code> method. * @param request servlet request * @param response servlet response */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP <code>POST</code> method. * @param request servlet request * @param response servlet response */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Returns a short description of the servlet. */ public String getServletInfo() { return "Short description"; } // </editor-fold> }
web.xml中的xml配置文件:
<!-- flex 文件上传 --> <servlet> <servlet-name>FileUploaded</servlet-name> <servlet-class>com.web.action.FileUploaded</servlet-class> </servlet> <servlet-mapping> <servlet-name>FileUploaded</servlet-name> <url-pattern>/FileUploaded</url-pattern> </servlet-mapping>