經常會設計一個這樣的功能,比如更改個性頭像,這個個性頭像最終需要上傳到伺服器的檔案系統中,但是程式希望在使用者選擇後直接有個預覽,然後使用者才進行上傳。這個功能技術上其實就是需要對本地的檔案能進行讀取。在flash player10中有個類FileReference的類可以實現這個功能,而實現對檔案讀取的介面是load( )函數,要注意的是:
a、這個函數只能在UI操作中使用,比如使用者按下按鈕。
b、載入進來後的本地檔案無法在AS中使用
c、這個介面是一個非同步過程,也就不是馬上就載入進來,需要加Listener來操作。
下面是參考代碼
複製代碼 代碼如下:
<?xml version="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"
creationComplete="creationCompleteHandler(event)">
<fx:Script>
<![CDATA[
import flash.net.FileReference;
import flash.net.FileFilter;
import flash.events.IOErrorEvent;
import flash.events.Event;
private var fr:FileReference;
private var imageTypes:FileFilter;
private function creationCompleteHandler(event:Event):void {
fr = new FileReference();
imageTypes = new FileFilter("Images (*.jpg, *.jpeg, *.png, *.gif)","*.jpg; *.jpeg; *.png; *.gif;")
fr.addEventListener(Event.SELECT, selectHandler);//增加當開啟瀏覽檔案後,使用者選擇好檔案後的Listener
}
private function browseHandler(event:Event):void {
fr.browse([imageTypes]);//開啟瀏覽檔案的dialog
}
private function selectHandler(event:Event):void {
fr.addEventListener(Event.COMPLETE, onLoadComplete);//增加一個檔案載入load完成後的listener
fr.load(); //載入使用者選中檔案
}
private function onLoadComplete(e:Event):void
{
imgPhoto.source = fr.data;
}
]]>
</fx:Script>
<s:layout>
<s:BasicLayout/>
</s:layout>
<fx:Declarations>
<!-- 將非可視元素(例如服務、值對象)放在此處 -->
</fx:Declarations>
<mx:Image id="imgPhoto" visible="true" autoLoad="true" width="1000" height="500"/>
<mx:Button id="btnBrowse" label="Browse" click="browseHandler(event)" />
</s:Application>