|
这个我做的是弹出的TitleWindow
主页代码简单,就是一个按钮
<?
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/halo" minWidth ="1024" minHeight ="768" > < s:layout > < s:BasicLayout /> </ s:layout > < fx:Script > <![CDATA[ import com.lichen.component.upload; import mx.managers.PopUpManager; protected function button1_clickHandler(event:MouseEvent):void { var win:upload=upload(PopUpManager.createPopUp(this,upload,true)); PopUpManager.centerPopUp(win); } ]]> </ fx:Script > < s:Button x ="36" y ="47" label ="按钮" click ="button1_clickHandler(event)" /> </ s:Application >
弹出的
TitleWindow是核心
<?
xml
version
="1.0"
encoding
="utf-8"
?>
< mx:TitleWindow xmlns:fx ="http://ns.adobe.com/mxml/2009" xmlns:s ="library://ns.adobe.com/flex/spark" xmlns:mx ="library://ns.adobe.com/flex/halo" layout ="absolute" title ="上传文件" color ="#7dbded" width ="609" height ="460" baseColor ="#E0ECFF" borderColor ="#E0ECFF" backgroundColor ="haloBlue" backgroundAlpha ="0.1" contentBackgroundAlpha ="0.1" borderVisible ="true" dropShadowVisible ="true" showCloseButton ="true" close ="PopUpManager.removePopUp(this)" fontFamily ="Arial" fontSize ="14" fontWeight ="bold" verticalAlign ="top" initialize ="init();" > < fx:Script > <![CDATA[ import mx.collections.ArrayCollection; import mx.controls.Alert; import mx.controls.ProgressBar; import mx.managers.PopUpManager; private var fileList:FileReferenceList = new FileReferenceList(); //多选文件的list private var urlRequest:URLRequest = new URLRequest("http://192.168.1.205:9218/productshowshow/upload"); //处理文件上传的servlet [Bindable] public var selectedFiles: ArrayCollection = new ArrayCollection([]); //多选的文件分离成文件数组 private var fileListSize:uint=1; /** * 初始化 */ public function init():void{ fileList.addEventListener(Event.SELECT,fileSelectHandler); } /** *监听文件选择的处理函数 */ private function fileSelectHandler(event: Event): void { if(fileList.fileList.length>10){ Alert.show("一次最多只能上传10个文件"); }else{ for(var i:int=0;i < fileList.fileList.length;i++){ var f:FileReference = FileReference(fileList.fileList[i]); var obj:Object= new Object(); obj.fileName = f.name; obj.fileSize = f.size/1024; obj.fileType = f.type; obj.fileRefrence = f; fileListSize+=f.size; selectedFiles.addItem(obj); } if( fileListSize/(1024*1024) >100 ){ selectedFiles.removeAll(); Alert.show("文件总大小应小于100M"); } } // for each (var file: FileReference in fileList.fileList) // { // selectedFiles.addItem(file); // } } /** * 点击"浏览"按钮-->选择文件 */ protected function selectFile():void { //浏览文件,因为是FileReferenceList所以可以多选. 并用FileFilter过滤文件类型. fileList.browse([new FileFilter("图片文件 (*.jpg, *.jpeg, *.gif, *.png)", "*.jpg;*.jpeg;*.gif;*.png"),new FileFilter("所有文件 (*.*)","*.*")]); } /** * 逐个上传文件 */ private function uploadHandler(event:MouseEvent):void{ var file:FileReference; for(var i:int = 0 ;i < selectedFiles.length;i++){ file = FileReference(selectedFiles[i].fileRefrence); file.upload(urlRequest); } } /** * 上传一个文件,监听文件上传完成事件,递归调用. */ private function doSingleUploadFile():void{ if(selectedFiles.length >10){ selectedFiles.removeAll(); Alert.show("一次最多只能上传10个文件"); }else if( fileListSize/(1024*1024)>100 ){ selectedFiles.removeAll(); Alert.show("文件总大小应小于100M"); }else{ if (fileList.fileList.length > 0){ var f: FileReference = fileList.fileList.shift() as FileReference; f.addEventListener(Event.COMPLETE, doSingleUploadFileComplete); f.upload(urlRequest); } } } /** * 一个文件上传完成事件的处理函数,递归执行上传下一个文件. */ private function doSingleUploadFileComplete(event: Event):void{ var file: FileReference = event.target as FileReference; file.removeEventListener(Event.COMPLETE, doSingleUploadFileComplete); doSingleUploadFile(); } public function removeFile(f: FileReference): void { var index: int = selectedFiles.getItemIndex(f); if (index != -1) selectedFiles.removeItemAt(index); } ]]> </ fx:Script > < fx:Declarations > <!-- Place non-visual elements (e.g., services, value objects) here --> </ fx:Declarations > < mx:LinkButton x ="10" y ="23" textRollOverColor ="purple" textSelectedColor ="haloBlue" label ="选择本地文件" cornerRadius ="7" fontFamily ="中易宋体" fontSize ="14" fontWeight ="bold" fontStyle ="normal" textDecoration ="none" textAlign ="center" click ="selectFile()" /> < mx:DataGrid x ="12" y ="50" id ="dg" width ="587" height ="291" color ="#7dbded" contentBackgroundColor ="#E0ECFF" baseColor ="#E0ECFF" dataProvider ="{selectedFiles}" > < mx:columns > < mx:DataGridColumn headerText ="文件名" dataField ="fileName" width ="150" /> < mx:DataGridColumn headerText ="大小(kb)" dataField ="fileSize" width ="100" /> < mx:DataGridColumn headerText ="类型" dataField ="fileType" width ="70" /> < mx:DataGridColumn headerText ="上传状态" dataField ="" width="230" > < mx:itemRenderer > < fx:Component > < mx:HBox width ="130" paddingLeft ="2" horizontalGap ="2" > < fx:Script > <![CDATA[ override public function set data(value:Object):void{ super.data = value; data.fileRefrence.addEventListener(ProgressEvent.PROGRESS,progressHandler); data.fileRefrence.addEventListener(DataEvent.UPLOAD_COMPLETE_DATA,fini); } private function progressHandler(event:ProgressEvent):void{ // progress.setProgress(event.bytesLoaded,data.fileRefrence.size); // Alert.show("hahah"); // progress.setProgress(event.bytesLoaded, event.bytesTotal); var procent:uint=event.bytesLoaded/event.bytesTotal*100; // progress.label=procent+"###"; // if(procent==100){ //// progress.enabled=false; // progress.label="完成啦"; // } // data.fileRefrence.removeEventListener(ProgressEvent.PROGRESS,progressHandler); } public function fini(event: DataEvent):void{ progress.visible=true; progress.label="完成"; data.fileRefrence.removeEventListener(DataEvent.UPLOAD_COMPLETE_DATA,fini); } ]]> </ fx:Script > < mx:ProgressBar id ="progress" width ="80%" minimum ="0" maximum ="100" source ="{data.fileRefrence}" labelPlacement ="center" ><!-- 进度条显示文字 source="{data.fileRefrence}" progress="progress.label='%3%%';" label="%3%%" --> </ mx:ProgressBar > <!-- 取消按钮 source="{data.fileRefrence}" <mx:LinkButton width="20" toolTip="取消上传" click="cancel()" label="取消" icon="@Embed('image/cancel.png')"> <fx:Script> <![CDATA[ private function cancel():void{ data.fileRefrence.cancel(); progress.label = "已取消"; } ]]> </fx:Script> </mx:LinkButton> --> <!-- <mx:LinkButton width="20" click="deleteItem(event)" toolTip="从列表中删除" icon="@Embed('image/delete.png')"> <fx:Script> <![CDATA[ import mx.collections.ArrayCollection; private function deleteItem(event:MouseEvent):void { var s:ArrayCollection= this.parentDocument.selectedFiles as ArrayCollection; //取全局变量 var index:int=s.getItemIndex(data); if (index != -1){ s.removeItemAt(index); } } ]]> </fx:Script> </mx:LinkButton> --> </ mx:HBox > </ fx:Component > </ mx:itemRenderer > </ mx:DataGridColumn > </ mx:columns > </ mx:DataGrid > < s:Button x ="523" y ="373" label ="上传" id ="btn_upload" lineHeight ="0" click ="doSingleUploadFile();" /> </ mx:TitleWindow >
文件上传服务器端(Java)
package com.test;
import java.io.File; import java.io.IOException; 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; public class UploadFile extends HttpServlet { private static final long serialVersionUID = 5425836142860976977L; /** *//** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods. * @param request servlet request * @param response servlet response */ // 定义文件的上传路径 private String uploadPath = "d:\\"; // 限制文件的上传大小 private int maxPostSize = 100 * 1024 * 1024; //最大100M public UploadFile() { 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"); //保存文件到服务器中 DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(4096); ServletFileUpload upload = new ServletFileUpload(factory); upload.setHeaderEncoding( "utf-8"); upload.setSizeMax(maxPostSize); 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(); System.out.println(name); try { item.write( new File(uploadPath + name)); response.getWriter().write( "上传成功。"); } catch (Exception e) { e.printStackTrace(); response.getWriter().write(e.getMessage()); } } } } catch (FileUploadException e) { e.printStackTrace(); response.getWriter().write(e.getMessage()); System.out.println(e.getMessage() + "结束"); } } 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"; } }
由于itemRenderer的问题,文件删除和DataGrid的滚动造成进度条进度错乱的问题都没能解决.不是很满意,但至少实现了基本的多文件带进度条上传.
|