Java與Flex學習筆記(8)—-Flex帶進度條的多檔案上傳(基於Servlet)

來源:互聯網
上載者:User

      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")@Overrideprotected 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/




相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.