FLEX圖片預覽上傳

    這些天正在研究flex圖片預覽上傳功能,於是找了一些資料進行了整理,形成了比較完整的示例,在此給自己留下參考資料。

    需要以下兩個jar包:commons-fileupload-1.2.jar和commons-io-1.4.jar

 

    上代碼,flex代碼

   

  1. <?xml version="1.0" encoding="utf-8"?>   
  2. <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"   
  3.                 layout="absolute"   
  4.                 xmlns="*"   
  5.                 creationComplete="init();">   
  6.     <mx:Script>   
  7.         <![CDATA[   
  8.             import flash.events.*;   
  9.              
  10.             import mx.controls.Alert;   
  11.             import mx.events.CloseEvent;   
  12.             import mx.managers.CursorManager;   
  13.              
  14.             private var file:FileReference;   
  15.             private var byteArray:ByteArray;   
  16.             private var bitmapData:BitmapData;   
  17.             private var loader:Loader=new Loader();   
  18.              
  19.             private function init():void   
  20.             {   
  21.                 Security.allowDomain("*");   
  22.                 file=new FileReference();   
  23.                 file.addEventListener(Event.COMPLETE, fileReferenceCompleteHandler);   
  24.                 file.addEventListener(Event.SELECT, fileReferenceSelectHandler);   
  25.             }   
  26.              
  27.             //選擇上傳的圖片   
  28.             private function choose():void   
  29.             {   
  30.                 var imageTypes:FileFilter=new FileFilter("Images (*.jpg, *.jpeg, *.png)", "*.jpg;*.jpeg;*.png");   
  31.                 var allTypes:Array=new Array(imageTypes);   
  32.                 file.browse(allTypes);   
  33.                 //              file.browse();   
  34.             }   
  35.              
  36.             private function toUpload():void   
  37.             {   
  38.                 if (bitmapData == null)   
  39.                 {   
  40.                     Alert.show("請您先選擇要上傳的圖片");   
  41.                 }   
  42.                 else   
  43.                 {   
  44.                     Alert.show("上傳 " + file.name + " (共 " + Math.round(file.size) + " 字節)?", "確認上傳", Alert.YES | Alert.NO, null, proceedWithUpload);   
  45.                 }   
  46.             }   
  47.              
  48.             //監聽文件上傳狀態   
  49.             private function onProgress(e:ProgressEvent):void   
  50.             {   
  51.                 lbProgress.text=" 已上傳 " + e.bytesLoaded + " 字節,共 " + e.bytesTotal + " 字節";   
  52.                 var proc:uint=e.bytesLoaded / e.bytesTotal * 100;   
  53.                 bar.setProgress(proc, 100);   
  54.                 bar.label="當前進度: " + " " + proc + "%";   
  55.                 if (e.bytesLoaded == e.bytesTotal)   
  56.                 {   
  57.                     CursorManager.removeBusyCursor();   
  58.                 }   
  59.             }   
  60.              
  61.             //上傳圖片到服務器   
  62.             private function proceedWithUpload(e:CloseEvent):void   
  63.             {   
  64.                 if (e.detail == Alert.YES)   
  65.                 {   
  66.                     //進度監聽   
  67.                     file.addEventListener(ProgressEvent.PROGRESS, onProgress);   
  68.                     var request:URLRequest=new URLRequest("http://localhost:8080/upload_1/servlet/upload");   
  69.                     //設置鼠標忙狀態   
  70.                     CursorManager.setBusyCursor();   
  71.                     try   
  72.                     {   
  73.                         file.upload(request);   
  74.                         Alert.show("恭喜你,上傳成功");   
  75.                     }   
  76.                     catch (error:Error)   
  77.                     {   
  78.                         Alert.show("上傳失敗");   
  79.                         trace("上傳失敗");   
  80.                     }   
  81.                      
  82.                 }   
  83.             }   
  84.              
  85.             //上傳完成調用   
  86.             private function completeHandle(event:Event):void   
  87.             {   
  88.                 Alert.show("恭喜你,上傳成功");   
  89.             }   
  90.              
  91.             //載入本地圖片   
  92.             private function fileReferenceCompleteHandler(e:Event):void   
  93.             {   
  94.                 byteArray=file.data;   
  95.                 loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loaderCompleteHandler);   
  96.                 loader.loadBytes(byteArray);   
  97.             }   
  98.              
  99.             //圖片載入完成顯示在預覽框中   
  100.             private function loaderCompleteHandler(e:Event):void   
  101.             {   
  102.                 var bitmap:Bitmap=Bitmap(loader.content);   
  103.                 bitmapData=bitmap.bitmapData;   
  104.                 img.source=bitmap;   
  105.             }   
  106.              
  107.             //選擇文件動作監聽   
  108.             private function fileReferenceSelectHandler(e:Event):void   
  109.             {   
  110.                 file.removeEventListener(ProgressEvent.PROGRESS, onProgress);   
  111.                 file.load();   
  112.             }   
  113.         ]]>   
  114.     </mx:Script>   
  115.      
  116.     <mx:Canvas width="100%"  height="100%"  x="10"  y="10"  fontSize="15">  
  117.         <mx:Panel width="469"   
  118.                   height="392"   
  119.                   verticalGap="0"   
  120.                   horizontalAlign="left"   
  121.                   verticalAlign="top"   
  122.                   x="0"   
  123.                   y="0"   
  124.                   layout="absolute">   
  125.             <mx:Image id="img"  width="400"  height="300"  x="36"  y="44"/>   
  126.         </mx:Panel>  
  127.         <mx:Button label="選擇文件"  click="choose();"  x="500"  y="400"/>  
  128.         <mx:VBox id="shangchuan" width="100%"  horizontalAlign="center" visible="true">   
  129.             <mx:Label id="lbProgress"  text="上傳"/>   
  130.             <mx:ProgressBar id="bar"   
  131.                             labelPlacement="bottom"   
  132.                             minimum="0"   
  133.                             visible="true"   
  134.                             maximum="100"   
  135.                             label="當前進度: 0%"   
  136.                             direction="right"   
  137.                             mode="manual"   
  138.                             width="200"/>   
  139.             <mx:Button label="上傳文件"  click="toUpload();"/>   
  140.         </mx:VBox>   
  141.     </mx:Canvas>   
  142. </mx:Application>  

後臺servlet:

 

  1. /** 
  2.      * get及post提交方式 
  3.      *  
  4.      * @param request 
  5.      * @param response 
  6.      * @throws ServletException 
  7.      * @throws IOException 
  8.      */ 
  9.     @SuppressWarnings({ "rawtypes""unchecked" }) 
  10.     public void doGetAndPost(HttpServletRequest request, 
  11.             HttpServletResponse response) throws ServletException, IOException { 
  12.         request.setCharacterEncoding("GBK"); 
  13.         // 文件存放的目錄 
  14.         //C:\\Documents and Settings\\jnzbht\\Workspaces\\MyEclipse 8.5\\upload\\WebRoot\\upload\\ 
  15.         File tempDirPath = new File(request.getSession().getServletContext().getRealPath("/")+ "\\upload\\"); 
  16.         if (!tempDirPath.exists()) { 
  17.             tempDirPath.mkdirs(); 
  18.         } 
  19.  
  20.         // 創建磁盤文件工廠 
  21.         DiskFileItemFactory fac = new DiskFileItemFactory(); 
  22.          
  23.         // 創建servlet文件上傳組件 
  24.         ServletFileUpload upload = new ServletFileUpload(fac); 
  25.          
  26.         //使用utf-8的編碼格式處理數據 
  27.         upload.setHeaderEncoding("utf-8");  
  28.          
  29.         // 文件列表 
  30.         List fileList = null
  31.          
  32.         // 解析request從而得到前臺傳過來的文件 
  33.         try { 
  34.             fileList = upload.parseRequest(request); 
  35.         } catch (FileUploadException ex) { 
  36.             ex.printStackTrace(); 
  37.             return
  38.         } 
  39.         // 保存後的文件名 
  40.         String imageName = null
  41.         // 便利從前臺得到的文件列表 
  42.          
  43.         Iterator<FileItem> it = fileList.iterator(); 
  44.          
  45.          
  46.         while (it.hasNext()) { 
  47.              
  48.             FileItem item = it.next(); 
  49.             // 如果不是普通表單域,當做文件域來處理 
  50.             if (!item.isFormField()) { 
  51.                 //生成四位隨機數 
  52.                 Random r = new Random(); 
  53.                 int rannum = (int) (r.nextDouble() * (9999 - 1000 + 1)) + 1000;  
  54.                  
  55.                 imageName = DateUtil.getNowStrDate() +  rannum 
  56.                         + item.getName(); 
  57.  
  58.                 BufferedInputStream in = new BufferedInputStream(item 
  59.                         .getInputStream()); 
  60.                 BufferedOutputStream out = new BufferedOutputStream( 
  61.                         new FileOutputStream(new File(tempDirPath + "\\" 
  62.                                 + imageName))); 
  63.                 Streams.copy(in, out, true); 
  64.  
  65.             } 
  66.         } 
  67.     } 

源碼見附件

訪問路徑爲
http://localhost:8080/upload_1/upload/upload.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章