今天花了一點時間研究了一下FLEX的檔案上傳,後台採用PHP進行處理。本文的代碼是整合了網上
尋找到的一些代碼,都是轉載來轉載去的,原文已經不可考,就不一一在這裡列出,感謝前人的分享
精神,向他們學習吧。
1. 首先先介紹點基本知識,php端的全域變數$_FILES數組
$_FILES['userfile']['name'] 用戶端機器檔案的原名稱。
$_FILES['userfile']['type'] 檔案的 MIME 類型,需要瀏覽器提供該資訊的支援,例如“image/gif”。
$_FILES['userfile']['size'] 已上傳檔案的大小,單位為位元組。
$_FILES['userfile']['tmp_name']檔案被上傳後在服務端儲存的臨時檔案名稱。
$_FILES['userfile']['error'] 和該檔案上傳相關的錯誤碼。
2. php檔案上傳大小設定
file_uploads =
on //是否允許系統支援檔案上傳
;upload_tmp_dir //臨時檔案的儲存路徑,如果不設定就是系統預設的路徑
upload_max_filesize = 2m //允許檔案上傳最大體積
post_max_size = 2m
//通過post方法給php時,php所能接受的最大資料容量
max_execution_time = 30
//每個script所執行的最大時間
memory_limit = 8m
//每個script所能消耗的最大memory
上面這些值都是php.ini的預設值,如果我們要傳更大的檔案,需要對當中的某些具體參數進行修改
一般上傳的檔案的資訊都是儲存在了$_FILES數組中,我們先來看一下PHP端如何處理。我們知道用戶端上傳的
檔案儲存在了系統預設的臨時檔案夾中,我們的目標就是要將臨時檔案夾中的檔案拷貝到我們需要儲存的地址當中去。
我們先來看一下PHP端的代碼,將一一做出解釋:
<?php<br />echo "/n temporary file name = " . $_FILES['Filedata']['tmp_name']."/n";<br />echo " file name = " . $_FILES['Filedata']['name']."/n";<br />echo " file size = " . $_FILES['Filedata']['size']."/n";<br />echo " attempting to move file.../n";<br />$uploaddir = './upload/images/';<br />//$filename = date("Ymdhis").rand(100,999);<br />$filename = date("Ymdhis").mt_rand(1000,9999);<br /> $uploadfile = $uploaddir .$filename.substr($_FILES['Filedata']["name"],strrpos($_FILES['Filedata']["name"],"."));<br /> if($uploadfile){<br />$file_size_max = 8*1024*1024;// 8M限制檔案上傳最大容量(bytes)<br />$accept_overwrite = 1;//是否允許覆蓋相同的檔案<br />if ($upload_file_size > $file_size_max) {<br />echo "對不起,你的檔案大小大於規定的上傳限制";<br />exit;<br />}<br /> }<br />if (file_exists($uploadfile) && $accept_overwrite) {<br />Echo "存在相同的檔案名稱";<br />exit;<br />}<br />$moved = move_uploaded_file($_FILES['Filedata']['tmp_name'],$uploadfile);<br />if(empty($moved))<br />{<br />echo"複製檔案失敗";<br />exit;<br />}<br />echo " file moved " . $moved . "/n";<br />$errorNo=$_FILES['upload_file']['error'];<br />switch($errorNo){<br />case 0:<br />Echo "上傳成功"; break;<br />case 1:<br />Echo "上傳的檔案超過了 php.ini 中 upload_max_filesize 選項限制的值."; break;<br />case 2:<br />Echo "上傳檔案的大小超過了 HTML 表單中 MAX_FILE_SIZE 選項指定的值。"; break;<br />case 3:<br />Echo "檔案只有部分被上傳";break;<br />case 4:<br />Echo "沒有檔案被上傳";break;<br />}<br />?>
PHP端的代碼比較簡單,對上傳的檔案產生了一個獨一無二的檔案名稱,並對檔案大小,檔案名稱唯一性進行了簡單的判斷,
最後使用php的move_upload_flie函數來實現檔案的移動。對於隨即數,可以使用rand和mt_rand函數,據說mt_rand
要比rand要快很多,有興趣的同學可以自己寫個測試程式測試一下。
現在我們轉到前端FLEX處理,Flex採用actionscript語言+xml語言。代碼中有詳細的注釋,就不做詳細說明了。
<?xml version="1.0" encoding="utf-8"?><br /><mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"<br />backgroundColor="#ffffff"><br /><mx:Style source="styles/styles.css" /><br /><mx:HRule x="10" y="37" width="90%"/><br /><mx:Text x="10" y="10" text="Uploading a File" styleName="headerStyle" id="label1"/><br /><mx:Script><br /><!--[CDATA[<br />// ENTER THE PATH TO THE FILE UPLOAD SCRIPT ON YOUR SERVER<br />public var uploadFile:String = "http://localhost:8080/php/UpAndDownLoad/php/file_upload.php";<br />]]><br /></mx:Script><br /><mx:Button x="10" y="70" label="Upload" click="{upload()}"/><br /><mx:Button x="83" y="70" label="Check if php file exists" click="{test()}"/><br /><mx:Script><br /><![CDATA[<br />import flash.net.navigateToURL;<br />import flash.events.DataEvent;<br />import mx.events.CloseEvent;<br />import mx.controls.Alert;<br />import flash.events.*;<br />// we declare the file reference here so it is not destroyed by memory garbage collection<br />public var fileRef:FileReference = new FileReference();<br />// a class that is similar to a HTML form<br />public var request:URLRequest;</p><p>// opens a browser window for the user to select a file to upload<br />public function upload():void {<br />// listen for the upload events<br />fileRef.addEventListener(Event.SELECT, selectHandler);fileRef.addEventListener(Event.OPEN, openHandler);fileRef.addEventListener(ProgressEvent.PROGRESS, progressHandler);fileRef.addEventListener(Event.COMPLETE, completeHandler);fileRef.addEventListener(DataEvent.UPLOAD_COMPLETE_DATA, uploadCompleteHandler);fileRef.addEventListener(SecurityErrorEvent.SECURITY_ERROR, httpSecurityErrorHandler);fileRef.addEventListener(HTTPStatusEvent.HTTP_STATUS, httpErrorHandler);fileRef.addEventListener(IOErrorEvent.IO_ERROR, httpIOErrorHandler);<br />// browse for the file to upload<br />// when user selects a file the select handler is called<br />try {<br />var imageTypes:FileFilter = new FileFilter("Images (*.jpg, *.jpeg, *.png)", "*.jpg;*.jpeg;*.png");<br /> var allTypes:Array = new Array(imageTypes);<br /> var success:Boolean = fileRef.browse(allTypes);<br />}<br />catch (error:Error) {<br /> trace("Unable to browse for files.");<br /> textarea1.text = "Unable to browse for files.";<br />}<br />}<br />// checks that the upload php file is where we think it is<br />public function test():void {<br /> request = new URLRequest(uploadFile);<br />navigateToURL(request,"_blank");<br />}</p><p>// when a file is selected we upload the file to the php file upload script on the server<br />public function selectHandler(event:Event):void {</p><p> try {<br /> // upload file<br /> Alert.show("上傳 " + fileRef.name + " (共 "+Math.round(fileRef.size)+" 位元組)?",<br /> "確認上傳",<br /> Alert.YES|Alert.NO,<br /> null,<br /> proceedWithUpload);<br /> //fileRef.upload(request);<br /> textarea1.text = "Uploading " + fileRef.name + "...";<br /> }<br /> catch (error:Error) {<br /> // vague<br /> trace("Unable to upload file.");<br /> textarea1.text += "/nUnable to upload file.";<br /> }<br />}<br />private function proceedWithUpload(e: CloseEvent): void{<br /> if (e.detail == Alert.YES){<br /> request = new URLRequest(uploadFile);<br /> try {<br /> fileRef.upload(request);<br /> } catch (error:Error) {<br /> Alert.show("上傳失敗");<br /> }<br /> }<br /> }<br />// dispatched during file open.<br />public function openHandler(event:Event):void {<br /> trace("File opened");<br /> textarea1.text += "/nFile opened";<br />}</p><p> // dispatched during file upload<br />public function progressHandler(event:ProgressEvent):void {<br /> trace("File upload in progress (" + event.bytesLoaded + " of " + event.bytesTotal + ")");<br /> textarea1.text += "/nFile upload in progress (" + event.bytesLoaded + " of " + event.bytesTotal + ")";<br /> lbProgress.text = " 已上傳 " + event.bytesLoaded<br /> + " 位元組,共 " + event.bytesTotal + " 位元組";<br /> var proc: uint = event.bytesLoaded / event.bytesTotal * 100;<br /> bar.setProgress(proc, 100);<br /> bar.label= "當前進度: " + " " + proc + "%";<br />}<br />// dispatched when the file has been given to the server script<br />// this event does not receive a response from the server<br />// use DataEvent.UPLOAD_COMPLETE_DATA event as shown in uploadCompleteHandler<br />public function completeHandler(event:Event):void {<br /> trace("File uploaded");<br /> textarea1.text += "/nFile uploaded";<br /> Alert.show("恭喜你,上傳成功");<br />}<br />// dispatched when a file upload has completed<br />// this event can contain a response from the server as opposed to the Event.COMPLETE event<br />// the php upload file can send back information if we want it to<br />// the event.data and event.text properties would contain a response if any<br />public function uploadCompleteHandler(event:DataEvent):void {<br /> trace("Information about upload: /n" + String(event.text));<br /> textarea1.text += "/nInformation about upload /n" + event.text as String;<br />}</p><p>// dispatched when an http error occurs<br />public function httpErrorHandler(event:HTTPStatusEvent):void {<br /> trace("HTTP error occured " + event.status);<br /> textarea1.text += "/nHTTP error occured - " + event.status;<br />}</p><p>// dispatched when an http io error occurs<br />public function httpIOErrorHandler(event:IOErrorEvent):void {<br /> trace("HTTP IO error occured - " + event.text);<br /> textarea1.text += "/nHTTP IO error occured - " + event.text;<br />}</p><p>// dispatched when an http io error occurs<br />public function httpSecurityErrorHandler(event:SecurityErrorEvent):void {<br /> trace("HTTP Security error occured - " + event.text);<br /> textarea1.text += "/nHTTP Security error occured - " + event.text;<br />}</p><p>]]--><br /></mx:Script></p><p><mx:TextArea x="10" y="100" width="90%" height="200" id="textarea1"/><br /> <mx:Label id="lbProgress" text="上傳" x="10" y="321" fontSize="12"/><br /> <mx:ProgressBar id="bar" labelPlacement="bottom" themeColor="#F20D7A"<br /> minimum="0" visible="true" maximum="100" label="當前進度: 0%"<br /> direction="right" mode="manual" width="200" x="10" y="349" fontSize="12"/> </p><p></mx:Application><br />