使用 Flex 和Java servlets 将文件上传到 RED5 服务器的步骤

来源:互联网 发布:java 浅拷贝 编辑:程序博客网 时间:2024/04/29 10:26

本文示例资源下载地址

        本文使用一个 demo 来演示如何使用 Flex 和 Java servlets 上传一个任意类型的本地文件到 RED5 服务器。使用的是 Flex 的 FileReference 接口,该接口可以对远程服务器上的文件进行上传、下载。FileReference 类提供了一个对话框接口和一个 upload 方法,通过该对话框,选择本地文件,而 upload 方法将会调用远程服务器端的 PHP,ASP 或者 Java 代码来进行上传。
        首先创建一个 Flex3 应用程序,该程序获得本地文件,并调用 RED5 服务器 "http://localhost:5080/Red5FileUploadProj/fileupload" 的 servlet。

        UploadToRed5Proj.mxml 源代码如下:

[html] view plaincopyprint?
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" xmlns:net="flash.net.*" layout="absolute" creationComplete="doInit()">  
  3.   <mx:Panel horizontalCenter="0" verticalCenter="0" verticalAlign="middle" horizontalAlign="center" borderColor="#FFFFFF" width="100%" height="100%" backgroundColor="#307CB7">  
  4.     <mx:Script>  
  5.       <![CDATA[ 
  6.         import mx.collections.ArrayCollection; 
  7.     import mx.controls.Alert; 
  8.     [Bindable]private var fileReference:FileReference; 
  9.     [Bindable]private var fileSelected:Boolean = false; 
  10.     [Bindable]private var serverUrl:String = "http://localhost:5080/Red5FileUploadProj/fileupload";      
  11.     private var statusArray:Array = new Array();  
  12.     [Bindable]private var statusArrayCollection:ArrayCollection = new ArrayCollection();  
  13.     private function doInit():void 
  14.     { 
  15.       fileReference = new FileReference(); 
  16.       fileReference.addEventListener(Event.SELECT, onFileSelect); 
  17.       fileReference.addEventListener(Event.COMPLETE, onUploadComplete); 
  18.       fileReference.addEventListener(ProgressEvent.PROGRESS,onUploadProgress); 
  19.       fileReference.addEventListener(IOErrorEvent.IO_ERROR, onUploadError); 
  20.       fileReference.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onUploadError); 
  21.     } 
  22.     private function browseFile(event:MouseEvent):void 
  23.     { 
  24.       fileReference.browse(); 
  25.     } 
  26.     private function onFileSelect(event:Event):void 
  27.     { 
  28.       fileSelected = true; 
  29.       fileTxt.text = fileReference.name; 
  30.       statusArray.push({status:"Ready to upload "+fileTxt.text});            
  31.       statusArrayCollection = new ArrayCollection(statusArray); 
  32.     } 
  33.     private function uploadFile(event:MouseEvent):void 
  34.     { 
  35.       if (!fileSelected || (urlTxt.text.length == 0)) 
  36.       { 
  37.         Alert.show("Select a file and Enter a URL"); 
  38.         return; 
  39.       } 
  40.       var urlRequest:URLRequest = new URLRequest(urlTxt.text); 
  41.       fileReference.upload(urlRequest); 
  42.     } 
  43.     private function onUploadProgress(event:ProgressEvent):void 
  44.     { 
  45.       statusArray.push({status:"In progress.."+((event.bytesLoaded * 100) / event.bytesTotal).toString()+"%"}); 
  46.       statusArrayCollection = new ArrayCollection(statusArray); 
  47.     } 
  48.     private function onUploadComplete(event:Event):void 
  49.     { 
  50.           statusArray.push({status:"Uploaded successfully!"}); 
  51.       statusArrayCollection = new ArrayCollection(statusArray); 
  52.     } 
  53.     private function onUploadError(event:Event):void 
  54.     { 
  55.       if (event is IOErrorEvent) 
  56.       { 
  57.         statusArray.push({status:"IO Error: "+(event as IOErrorEvent).text.toString()}); 
  58.         statusArrayCollection = new ArrayCollection(statusArray); 
  59.       } 
  60.       else if (event is SecurityErrorEvent) 
  61.       { 
  62.         statusArray.push({status:"Security Error: "+(event as IOErrorEvent).text.toString()}); 
  63.         statusArrayCollection = new ArrayCollection(statusArray); 
  64.       } 
  65.     } 
  66.       ]]>  
  67.     </mx:Script>  
  68.     <mx:VBox height="40%" width="30%" horizontalGap="0" horizontalAlign="left">  
  69.       <mx:HBox height="10%" width="100%" horizontalAlign="left">  
  70.         <mx:VBox height="100%" width="30%" horizontalAlign="left">  
  71.           <mx:Label text="File name"></mx:Label>  
  72.         </mx:VBox>  
  73.         <mx:VBox height="100%" width="40%" horizontalAlign="left">  
  74.           <mx:TextInput id="fileTxt" width="200" editable="false" toolTip="Select File to upload"/>  
  75.     </mx:VBox>  
  76.     <mx:VBox height="100%" width="30%" horizontalAlign="left">  
  77.       <mx:Button id="browseBut" label="Browse" click="browseFile(event)" />                 
  78.     </mx:VBox>  
  79.       </mx:HBox>  
  80.       <mx:HBox height="10%" width="100%" horizontalAlign="left">  
  81.         <mx:VBox height="100%" width="30%" horizontalAlign="left">  
  82.           <mx:Label text="Server URL"></mx:Label>  
  83.         </mx:VBox>  
  84.     <mx:VBox height="100%" width="70%" horizontalAlign="left">  
  85.       <mx:TextInput id="urlTxt" width="290" text="{serverUrl}"/>  
  86.     </mx:VBox>  
  87.       </mx:HBox>  
  88.       <mx:HBox height="10%" width="100%" horizontalAlign="center">  
  89.         <mx:Button id="uploadBut" label="Upload file" click="uploadFile(event)" enabled="{fileSelected}" />  
  90.       </mx:HBox>  
  91.       <mx:HBox height="70%" width="100%" horizontalAlign="center">  
  92.         <mx:DataGrid id="statusDG" width="100%" height="100%" dataProvider="{statusArrayCollection}" variableRowHeight="true" wordWrap="true">  
  93.       <mx:columns>      
  94.         <mx:DataGridColumn dataField="status" headerText="Upload Status" paddingLeft="0" paddingRight="0">  
  95.         </mx:DataGridColumn>  
  96.       </mx:columns>  
  97.             </mx:DataGrid>  
  98.       </mx:HBox>  
  99.     </mx:VBox>  
  100.   </mx:Panel>  
  101. </mx:Application>  


        服务器端的 Java Servlet 代码使用一个 Apache 的第三方类库 Commons FileUpload 包,它可以使我们的 servlets 或者 web 应用程序具有上传的功能。这个包可以从这里进行下载:http://commons.apache.org/fileupload/。Commons FileUpload 包内部使用了 Apache Commons IO 包,所以我们把这个包也下下来:http://commons.apache.org/io/。在本文的例子中,我使用的是 commons-fileupload-1.2.1.jar 和 commons-io-1.4.jar。将 commons-fileupload-1.2.1.jar、commons-io-1.4.jar 和 servlet-api.jar 复制到 RED5 项目的 /WEB-INF/lib 目录下。其中 servlet-api.jar 可以去 tomcat 安装目录下的 lib 文件夹下去找。

        然后,在我们的 RED5 应用程序的 web.xml 文件夹下添加如下内容:

[html] view plaincopyprint?
  1. <servlet>          
  2.   <servlet-name>fileupload</servlet-name>  
  3.   <servlet-class>com.mycompany.ind.red5.FileUploadServlet</servlet-class>  
  4.     <init-param>  
  5.       <param-name>uploadFolder</param-name>  
  6.       <param-value>uploads</param-value>  
  7.     </init-param>  
  8. </servlet>  
  9. <servlet-mapping>  
  10.   <servlet-name>fileupload</servlet-name>  
  11.   <url-pattern>/fileupload</url-pattern>  
  12. </servlet-mapping>  


        如果你熟悉 JEE,你会发现和 tomcat 的 web.xml 配置基本一致:servlet-mapping 元素将匹配 /fileupload 的 url 到名为 "fileupload" 的 servlet,servlet 元素则指示出该 servlet 具体实现类;上传的文件夹名作为 servlet 的初始参数也在这里进行定义,这里定义为 "uploads",所以应该在我们的 RED5 项目根目录下创建一个同名文件夹。

        最后,写具体实现上传的 FileUploadServlet 类:

[java] view plaincopyprint?
  1. package com.mycompany.ind.red5;  
  2. import javax.servlet.ServletException;  
  3. import javax.servlet.http.HttpServlet;  
  4. import javax.servlet.http.HttpServletRequest;  
  5. import javax.servlet.http.HttpServletResponse;  
  6. import org.apache.commons.fileupload.FileItem;  
  7. import org.apache.commons.fileupload.FileItemFactory;  
  8. import org.apache.commons.fileupload.FileUploadException;  
  9. import org.apache.commons.fileupload.disk.DiskFileItemFactory;  
  10. import org.apache.commons.fileupload.servlet.ServletFileUpload;  
  11. import java.io.IOException;  
  12. import java.util.Iterator;  
  13. import java.util.List;  
  14. import java.io.FileOutputStream;  
  15. import java.io.FileNotFoundException;  
  16.   
  17. public class FileUploadServlet extends HttpServlet  
  18. {  
  19.   @Override  
  20.   protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException  
  21.   {  
  22.     super.doGet(request, response);  
  23.     doPost(request,response);  
  24.   }  
  25.   @Override  
  26.   public void doPost( HttpServletRequest request, HttpServletResponse response )  
  27.   {  
  28.     /** 
  29.      * Create a factory for new disk-based file items 
  30.      */  
  31.     FileItemFactory factory = new DiskFileItemFactory();  
  32.     /** 
  33.      * Create a new file upload handler 
  34.      */  
  35.     ServletFileUpload upload = new ServletFileUpload(factory);  
  36.     try  
  37.     {  
  38.       /** 
  39.        * Parsing input request 
  40.        */  
  41.       List items = upload.parseRequest(request);  
  42.       /** 
  43.        * Process the uploaded items 
  44.        */  
  45.       Iterator iter = items.iterator();  
  46.       while (iter.hasNext())   
  47.       {  
  48.         FileItem item = (FileItem) iter.next();              
  49.     /** 
  50.      * handling a normal form-field 
  51.      */  
  52.         if (item.isFormField())   
  53.        {  
  54.           System.out.println("A form field");                   
  55.         }   
  56.     else   
  57.     {  
  58.            /** 
  59.         * handling file uploads 
  60.         */  
  61.           System.out.println("Not a form field");  
  62.       String uploadFileName = item.getName();  
  63.       byte[] data = item.get();  
  64.       /** 
  65.        * Gets directory to which the file is to be uploaded 
  66.        */  
  67.           String uploadFolder = getServletConfig().getInitParameter("uploadFolder");  
  68.       String fileFolderName = getServletContext().getRealPath(uploadFolder + "\\"+uploadFileName);  
  69.       try  
  70.       {  
  71.             FileOutputStream fileOutSt = new FileOutputStream(fileFolderName);  
  72.         try  
  73.         {  
  74.           fileOutSt.write(data);  
  75.           fileOutSt.close();  
  76.         }  
  77.             catch(IOException exception)  
  78.         {  
  79.           exception.printStackTrace();  
  80.         }  
  81.           }  
  82.       catch(FileNotFoundException exception)  
  83.       {  
  84.             exception.printStackTrace();  
  85.       }  
  86.     }  
  87.       }  
  88.     }  
  89.     catch(FileUploadException exception)  
  90.     {             
  91.       exception.printStackTrace();  
  92.     }  
  93.   }  
  94. }