Friday, April 13, 2012

AS3: Load a image without uploading it

In the past, if you want to create a flash site that allows user to upload their own image, you probably would need to upload the image to a server and retrieve it back after uploading. This can be quite lame. But in Flash Player 10 onwards, you can throw the step of connecting to a server away and attract the file you have uploaded immediately.

Time to take a look at some codes:
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="" 
    layout="absolute" horizontalAlign="center"
     verticalAlign="middle" width="100%"
   import mx.utils.Base64Encoder;
   private var fileRef:FileReference = new FileReference();
   //On Clicking on button 'browse', show dialog box
   //that only allows either jpg or gif or png.
   protected function clickHandler(event:MouseEvent):void
    fileRef.browse([new FileFilter("Images", "*.jpg;*.gif;*.png")]);
    fileRef.addEventListener(Event.SELECT, onFileSelected);
   //After the user has make a selection, 
   protected function onFileSelected(e:Event):void {
    fileRef.addEventListener(Event.COMPLETE, onFileLoaded);
   //load the image onto the Image component.
   //And you are done.
   protected function onFileLoaded(e:Event):void {
 <mx:VBox horizontalAlign="center" verticalAlign="middle"
    paddingBottom="10" paddingLeft="10" 
    paddingRight="10" paddingTop="10"
    width="100%" height="100%">
  <mx:Button id="browse" label="Browse" click="clickHandler(event)"/>
  <mx:Image id="imgLoader"/>

* Click here for the demo.
^ Click here for the source files.

No comments:

Post a Comment