使用 Flex 和Java servlets 將檔案上傳到 RED5 伺服器的步驟
本文樣本資源
本文使用一個 demo 來示範如何使用 Flex 和 Java servlets 上傳一個任意類型的本地檔案到 RED5 伺服器。使用的是 Flex 的 FileReference 介面,該介面可以對遠程伺服器上的檔案進行上傳、下載。FileReference 類提供了一個對話方塊介面和一個 upload 方法,通過該對話方塊,選擇本地檔案,而 upload 方法將會調用遠程伺服器端的 PHP,ASP 或者 Java 代碼來進行上傳。
首先建立一個 Flex3 應用程式,該程式獲得本地檔案,並調用 RED5 伺服器 "http://localhost:5080/Red5FileUploadProj/fileupload" 的 servlet。
UploadToRed5Proj.mxml 原始碼如下:
<?xml version="1.0" encoding="utf-8"?><mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" xmlns:net="flash.net.*" layout="absolute" creationComplete="doInit()"> <mx:Panel horizontalCenter="0" verticalCenter="0" verticalAlign="middle" horizontalAlign="center" borderColor="#FFFFFF" width="100%" height="100%" backgroundColor="#307CB7"> <mx:Script> <![CDATA[ import mx.collections.ArrayCollection;import mx.controls.Alert;[Bindable]private var fileReference:FileReference;[Bindable]private var fileSelected:Boolean = false;[Bindable]private var serverUrl:String = "http://localhost:5080/Red5FileUploadProj/fileupload";private var statusArray:Array = new Array(); [Bindable]private var statusArrayCollection:ArrayCollection = new ArrayCollection(); private function doInit():void{ fileReference = new FileReference(); fileReference.addEventListener(Event.SELECT, onFileSelect); fileReference.addEventListener(Event.COMPLETE, onUploadComplete); fileReference.addEventListener(ProgressEvent.PROGRESS,onUploadProgress); fileReference.addEventListener(IOErrorEvent.IO_ERROR, onUploadError); fileReference.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onUploadError);}private function browseFile(event:MouseEvent):void{ fileReference.browse();}private function onFileSelect(event:Event):void{ fileSelected = true; fileTxt.text = fileReference.name; statusArray.push({status:"Ready to upload "+fileTxt.text}); statusArrayCollection = new ArrayCollection(statusArray);}private function uploadFile(event:MouseEvent):void{ if (!fileSelected || (urlTxt.text.length == 0)) { Alert.show("Select a file and Enter a URL"); return; } var urlRequest:URLRequest = new URLRequest(urlTxt.text); fileReference.upload(urlRequest);}private function onUploadProgress(event:ProgressEvent):void{ statusArray.push({status:"In progress.."+((event.bytesLoaded * 100) / event.bytesTotal).toString()+"%"}); statusArrayCollection = new ArrayCollection(statusArray);}private function onUploadComplete(event:Event):void{ statusArray.push({status:"Uploaded successfully!"}); statusArrayCollection = new ArrayCollection(statusArray);}private function onUploadError(event:Event):void{ if (event is IOErrorEvent) { statusArray.push({status:"IO Error: "+(event as IOErrorEvent).text.toString()}); statusArrayCollection = new ArrayCollection(statusArray); } else if (event is SecurityErrorEvent) { statusArray.push({status:"Security Error: "+(event as IOErrorEvent).text.toString()}); statusArrayCollection = new ArrayCollection(statusArray); }} ]]> </mx:Script> <mx:VBox height="40%" width="30%" horizontalGap="0" horizontalAlign="left"> <mx:HBox height="10%" width="100%" horizontalAlign="left"> <mx:VBox height="100%" width="30%" horizontalAlign="left"> <mx:Label text="File name"></mx:Label> </mx:VBox> <mx:VBox height="100%" width="40%" horizontalAlign="left"> <mx:TextInput id="fileTxt" width="200" editable="false" toolTip="Select File to upload"/></mx:VBox><mx:VBox height="100%" width="30%" horizontalAlign="left"> <mx:Button id="browseBut" label="Browse" click="browseFile(event)" /></mx:VBox> </mx:HBox> <mx:HBox height="10%" width="100%" horizontalAlign="left"> <mx:VBox height="100%" width="30%" horizontalAlign="left"> <mx:Label text="Server URL"></mx:Label> </mx:VBox><mx:VBox height="100%" width="70%" horizontalAlign="left"> <mx:TextInput id="urlTxt" width="290" text="{serverUrl}"/></mx:VBox> </mx:HBox> <mx:HBox height="10%" width="100%" horizontalAlign="center"> <mx:Button id="uploadBut" label="Upload file" click="uploadFile(event)" enabled="{fileSelected}" /> </mx:HBox> <mx:HBox height="70%" width="100%" horizontalAlign="center"> <mx:DataGrid id="statusDG" width="100%" height="100%" dataProvider="{statusArrayCollection}" variableRowHeight="true" wordWrap="true"> <mx:columns> <mx:DataGridColumn dataField="status" headerText="Upload Status" paddingLeft="0" paddingRight="0"> </mx:DataGridColumn> </mx:columns> </mx:DataGrid> </mx:HBox> </mx:VBox> </mx:Panel></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 檔案夾下添加如下內容:
<servlet> <servlet-name>fileupload</servlet-name> <servlet-class>com.mycompany.ind.red5.FileUploadServlet</servlet-class> <init-param> <param-name>uploadFolder</param-name> <param-value>uploads</param-value> </init-param></servlet><servlet-mapping> <servlet-name>fileupload</servlet-name> <url-pattern>/fileupload</url-pattern></servlet-mapping>
如果你熟悉 JEE,你會發現和 tomcat 的 web.xml 配置基本一致:servlet-mapping 元素將匹配 /fileupload 的 url 到名為 "fileupload" 的 servlet,servlet 元素則指示出該 servlet 具體實作類別;上傳的檔案夾名作為 servlet 的初始參數也在這裡進行定義,這裡定義為 "uploads",所以應該在我們的 RED5 項目根目錄下建立一個同名檔案夾。
最後,寫具體實現上傳的 FileUploadServlet 類:
package com.mycompany.ind.red5;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.FileItemFactory;import org.apache.commons.fileupload.FileUploadException;import org.apache.commons.fileupload.disk.DiskFileItemFactory;import org.apache.commons.fileupload.servlet.ServletFileUpload;import java.io.IOException;import java.util.Iterator;import java.util.List;import java.io.FileOutputStream;import java.io.FileNotFoundException;public class FileUploadServlet extends HttpServlet{ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { super.doGet(request, response); doPost(request,response); } @Override public void doPost( HttpServletRequest request, HttpServletResponse response ) { /** * Create a factory for new disk-based file items */ FileItemFactory factory = new DiskFileItemFactory(); /** * Create a new file upload handler */ ServletFileUpload upload = new ServletFileUpload(factory); try { /** * Parsing input request */ List items = upload.parseRequest(request); /** * Process the uploaded items */ Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); /** * handling a normal form-field */ if (item.isFormField()) { System.out.println("A form field"); } else { /** * handling file uploads */ System.out.println("Not a form field"); String uploadFileName = item.getName(); byte[] data = item.get(); /** * Gets directory to which the file is to be uploaded */ String uploadFolder = getServletConfig().getInitParameter("uploadFolder"); String fileFolderName = getServletContext().getRealPath(uploadFolder + "\\"+uploadFileName); try { FileOutputStream fileOutSt = new FileOutputStream(fileFolderName); try { fileOutSt.write(data); fileOutSt.close(); } catch(IOException exception) { exception.printStackTrace(); } } catch(FileNotFoundException exception) { exception.printStackTrace(); }} } } catch(FileUploadException exception) { exception.printStackTrace(); } }}
如有問題,歡迎和作者進行線上交流,MSN:defonds#hotmail.com;email:defonds#163.com(#=@)。
部落格原文地址:http://tharas.wordpress.com/2009/12/20/upload-files-to-red5-server/。