The following example shows how you can browse for an image file from your local file system and preview the image before uploading it to a remote webserver by using the FileReference class’s new load() method in Flash Player 10. Once the user has browsed and selected an image from their local machine, you can call the load() method which dispatches a complete event when the image has successfully loaded, at which point you can display the image using a Flex Image control and setting the Image instance’s source property to the FileReference class’s data property (which is a ByteArray).

Full code after the jump.

The following example(s) require Flash Player 10 and the Adobe Flex 4 SDK. To download the Adobe Flash Builder 4 trial, see http://www.adobe.com/products/flex/. To download the latest nightly build of the Flex 4 SDK, see http://opensource.adobe.com/wiki/display/flexsdk/Download+Flex+4.
For more information on getting started with Flex 4 and Flash Builder 4, see the official Adobe Flex Team blog.

<?xml version="1.0" encoding="utf-8"?>
<!-- http://blog.flexexamples.com/2008/08/25/previewing-an-image-before-uploading-it-using-the-filereference-class-in-flash-player-10/ -->
<s:Application name="FileReference_load_test"
        xmlns:fx="http://ns.adobe.com/mxml/2009"
        xmlns:s="library://ns.adobe.com/flex/spark"
        xmlns:mx="library://ns.adobe.com/flex/halo"
        xmlns:net="flash.net.*">
 
    <fx:Script>
        <![CDATA[
            import mx.controls.Alert;
            import mx.utils.ObjectUtil;
 
            private function btn_click(evt:MouseEvent):void {
                var arr:Array = [];
                arr.push(new FileFilter("Images", ".gif;*.jpeg;*.jpg;*.png"));
                fileReference.browse(arr);
            }
 
            private function fileReference_select(evt:Event):void {
                fileReference.load();
            }
 
            private function fileReference_complete(evt:Event):void {
                img.source = fileReference.data;
                Alert.show(ObjectUtil.toString(fileReference));
            }
        ]]>
    </fx:Script>
 
    <fx:Declarations>
        <net:FileReference id="fileReference"
                select="fileReference_select(event);"
                complete="fileReference_complete(event);" />
    </fx:Declarations>
 
    <mx:Panel id="panel"
            layout="absolute"
            horizontalCenter="0"
            verticalCenter="0"
            width="500"
            height="300">
        <mx:Image id="img"
                verticalCenter="0"
                horizontalCenter="0"
                maxWidth="200"
                maxHeight="200" />
        <mx:ControlBar>
            <mx:Button id="btn"
                    label="Browse and preview..."
                    click="btn_click(event);" />
            <mx:Button label="Upload..."
                    enabled="false" />
        </mx:ControlBar>
    </mx:Panel>
 
</s:Application>

View source is enabled in the following example.

For more information on the new FileReference capabilities in Flash Player 10, see the Flex Gumbo documentation at http://livedocs.adobe.com/flex/gumbo/langref/flash/net/FileReference.html.

This entry is based on a beta version of the Flex 4 SDK and therefore is very likely to change as development of the Flex SDK continues. The API can (and will) change causing examples to possibly not compile in newer versions of the Flex 4 SDK.

 
Tagged with:
 
About The Author

Peter deHaan

Peter deHaan currently works for Adobe on the Flex SDK QA team. While not working on Flex, Flash, and ColdFusion applications, Peter enjoys making up bios and writing in 3rd person. Peter's rarely updated blog can be found at blogs.adobe.com/pdehaan/, actionscriptexamples.com, airexamples.com, and coldfusionexamples.com.

64 Responses to Previewing an image before uploading it using the FileReference class in Flash Player 10

  1. sergio says:

    thanks!
    btw why don’t colorize code my Flex Builder 3 (with installed Gumbo SDK) in <Script/> block?
    also code completion do not work too.
    i gues is for sake of xmlns="http://ns.adobe.com/mxml/2009"
    can i fix it some how?

  2. Kevin Eleven says:

    Nice to not have to actually upload the images before displaying them! ( I had to do that using v9 )

  3. Geert says:

    How would you do this in Flash player 9 exactly?

  4. peterd says:

    Geert,

    In Flash Player 9, you’d need to upgrade to Flash Player 10. (It’s a new feature in Flash Player 10)

    Peter

  5. Geert says:

    Hi Peter,

    Yes I understand. But my question was how you can preview the image an image before uploading it in Flash player 9 (not using the new Flash player 10). I’ve been looking for an example, but couldn’t find one up till now.

  6. peterd says:

    Geert,

    As far as I know, this is not possible in Flash Player 9, it was a new API/feature added in Flash Player 10.

    Peter

  7. acidguy says:

    possible to do with SDK3????…..

  8. peterd says:

    acidguy,

    I do not think this is possible with the Flex 3 SDK. Although you could try downloading the latest Flex 3.2 SDK and running this with Flash Player 10.

    Peter

  9. Stormbreaker says:

    peterd,

    this is possible in SDK 3.2 . I just had to do something like this and it works just fine!

    • Pushkar says:

      What exactly did you do to emulate this? Is there a way to create a thumbnail size preview this quick without having a thumbnail sized file along with a large file?

  10. deenalex says:

    Hi Everyone,

    Can any one help me to convert any type of Video files into .flv format (i.e) flash video format.

    I mean, if we browse and select any type of video, it (Flex Program) should convert it to .flv format.

    Thanks in Advance……

  11. Ryan Pieszak says:

    Hey Peter,

    Is there anyway to get the width and height of the image that’s loaded?

    Thanks,
    Ryan

  12. Peter deHaan says:

    Ryan Pieszak,

    Sure. If you’re sure the user selected an image, you could display the loaded ByteArray object into an Image control or Loader and then get the width/height (or contentWidth/contentHeight) after the Image/Loader has finished loading.

    Something like this if you’re using a Loader:

    private function fileReference_complete(evt:Event):void {
        img.source = fileReference.data;
        var ldr:Loader = new Loader();
        ldr.contentLoaderInfo.addEventListener(Event.COMPLETE, ldr_complete);
        ldr.loadBytes(fileReference.data);
    }
    
    private function ldr_complete(evt:Event):void {
        trace(evt.currentTarget.width, evt.currentTarget.height);
    }
    

    If you’re using the Image tag in the big example above, you could try something like the following:

    <Image id="img"
            verticalCenter="0"
            horizontalCenter="0"
            maxWidth="200"
            maxHeight="200"
            complete="trace(img.contentWidth, img.contentHeight);" />
    

    Hope that helps, Happy Flexing!
    Peter

  13. Ryan Pieszak says:

    Bingo! I was headed towards the second example, but trying to use img.width and img.height, and they weren’t giving me what I need. Thanks a lot for posting the examples!

  14. johnny says:

    Hello. I followed all the steps above and everything seemed to go well until I copy-pasted your code. Whatever I do it gives me a few errors. The problem is that although I’ve been using Flash & as3 for a while this is my first Flex project. Any help would be greatly appreciated. The main three errors are that Flex can’t find mx: Button, Image and Panel.
    The last error occurs when I click on the design tab. An error saying “An unknown item is declared as the root of your MXML document. Switch to source mode to correct it”.

    I have Adobe Flex builder 3 installed and got the latest version of Gumbo Flex SDK (nightly build). Also I added manually the SDK, checked the export for flash player 10 and downloaded the ocx needed for that flash player (I had only Flash CS3 so flash player 9). :-)

    I hope I was clear enough. :-)

  15. Scarlet sail says:

    Hi Peter,

    I am having the same problem like johnny’s. I also followed those step but when I tried to run your code, it returned some errors in the problem window:

    Could not resolve to a component implementation.
    Could not resolve to a component implementation.
    Could not resolve to a component implementation.

    In addition, when I set the RUN mode to call SWF for previewing, it also prompted me the following errors:

    VerifyError: Error #1053: Illegal override of scaleZ in mx.core.UIComponent.
     
    	at flash.display::MovieClip/nextFrame()
    	at mx.managers::SystemManager/deferredNextFrame()[E:\dev\gumbo_alpha\frameworks\projects\framework\src\mx\managers\SystemManager.as:318]
    	at mx.managers::SystemManager/preloader_initProgressHandler()[E:\dev\gumbo_alpha\frameworks\projects\framework\src\mx\managers\SystemManager.as:2947]
    	at flash.events::EventDispatcher/dispatchEventFunction()
    	at flash.events::EventDispatcher/dispatchEvent()
    	at mx.preloaders::Preloader/timerHandler()[E:\dev\gumbo_alpha\frameworks\projects\framework\src\mx\preloaders\Preloader.as:398]
    	at flash.utils::Timer/_timerDispatch()
    	at flash.utils::Timer/tick()

    I don’t know how to solve this, please help. Thank you so much!

  16. Scarlet sail says:

    Oh what happened with “, ,” tags, they didn’t display…I mean the first 3 error messages were about those.

  17. pao says:

    there’s an error..it wont compile due to the application..could you please check why this is..i already copied the mxml and installed the gumbo sdk

  18. randygland says:

    then how do u upload the user’s selected JPG!!?

  19. gotjosh says:

    Are there known issues with this on Mac??

  20. aap says:

    Hi,
    Can we use the bytearray from File reference object and use the thumbnail information in the JPEG to show preview of image of size>50MB.

  21. suresh says:

    Please Help

    Me i wanted to upload a jpeg file from the server crop it to the restricted size, user can keep the cropping size any where on the picture so that the particular thing is saved when we save it

    I am planning to do the above, i am a great fan of urs, i learn things from your site, but i am into trouble tried googling, various things but could not found out, so finally ended up beliving you can help me.

    Please suggest me something, i am facing issues with the above eg, even though i have flex builder 3.02, flashplayer 10 and flex sdk flex_sdk_4.0.0.4845

    i am facing the following errors

    A unknown item is declared as the root of your MXML document.Switch to source mode to correct it

    The prefix “net” for element “net:FileReference” is not bound.

  22. suresh says:

    Dear Peter,

    I was checking the site from Friday night more than 10 times , I know you ll be busy.
    Please let me know the solution once you are done :-) i am facing the bug.
    Thanks in advance

    Suresh

  23. hey Thanks for the source code.But how can i convert it to Flex 2? i have a project and cant upgrade to flex 3 right now. Any option how can i do this in Flex 2?

    Thank u so much

  24. Very nice. I’ll be playing around with it.

  25. ropo says:

    If Flex Builder tells you that .load() is undefined you have to select the correct SDK

    !AND!

    check “Require flash player version 10.0.0″

  26. is there any app out there or tutorial for as3? and flash? not flex?

    thanks

    here is a good one for you.

    I have used countless flash as3 uploaders. they all work.
    however, when flash goes to retrieve the image and show it in
    a photo gallery, or news slider, flash for some reason can not
    see that the image is there, and so it throws a error.

    if I upload the images by hand using ftp, flash has no problems
    seeing the images on the server. why is that?

  27. denns says:

    hi, i tried this using a filereferencelist for uploading multiple files, but now there is the problem that if i take bigger files (like from a digital camera) the browser will use about 1GB of RAM. Is there any possibility to reduce the ram usage somehow?? any different kind of loading the picture or downscale it somehow??

  28. kamrul says:

    i am very bigenner in flex. i am trying to load image using your reference but it showes some error when i complile it. pls can someone help me how can i do it……

  29. Ady Levy says:

    i’ve released a source code for image preview and manipulation before upload + php script for image reciving in server.

    check out : http://www.adylevy.com/index.php/2009/06/07/client-side-image-resize-flash-cs4-filereferencedata/

    Ady.

  30. Gilbert says:

    Peter,

    I tested it on Flex 3.3 and it works fine for images.

    Is it possible to load a video with a similar method?
    If so, how can be done?

    I tried, but the fileReference.data is a ByteArray and the video.source expects a String.

    Thanks,

    Gilbert

  31. Mike says:

    Thank you for the post.

    BTW. This method works just fine for Flex 3.3. Just make sure you change your ‘Requires Flash Player Version’ to at least 10.0.0.

  32. Tina says:

    Hi,
    I have Flex builder 3 and I also installed Adobe Flash Builder Beta SDK Command Prompt to get SDK 4.0, and I hoped that than I will be able to run this example. But there’s an error

    Unknown Flex SDK: “Flex 4.0.0.2968″ FileReference_load_test Unknown 1252256102796 5

    What’s wrong? Can anybody help me?

    Tina

  33. Bragadeesh says:

    Hey buddy,

    This is a cool article. Thanks!
    Cant I load Bitmap .bmp images??! I tried using a loader, but I got the following error

    Error #2044: Unhandled IOErrorEvent:. text=Error #2124: Loaded file is an unknown type.

    Thanks,
    Bragadeesh.

    • Peter deHaan says:

      @Bragadeesh,

      I don’t believe that .BMP is supported by Flash Player. I think it only loads .GIF, .JPEG, and .PNG files directly.

      Peter

      • Bragadeesh says:

        Oh.. Can you suggest a workaround to make them(.bmp .tiff) support as well?
        Any hint is greatly appreciated Peter.

        Thanks,
        Braga

      • Scott F. says:

        Hey guys,
        I was curious about the same thing as Bragadeesh. Has anyone found a quick way to load .bmp images directly? An example or a link to a description would be great.
        Thanks,
        Scott

  34. suganya says:

    Hi,
    Ur code is very nice.
    when i copy and paste ur code it shows error- what i have to change in code
    Could not resolve to a component implementation.

    Thanks in advance..

  35. Insane User says:

    I am using Ubuntu with Eclipse, how could I experiment with Flex 4.0 SDK?

  36. Rafal says:

    How to load *.SWF file without getting error:

    SecurityError: Error #3015: Loader.loadBytes() is not permitted to load content with executable code.

    Thanks for any help.

  37. neenu says:

    how to resize the image and then upload the modified image to server finally?

  38. Yann says:

    Thanks Peter for the tutorial !

    I am using fileReference in a project where I need to modify the image before sending it to my server (rotate, resize…)
    The issue is that fileReference.data is read only, therefore I cannot pass along the new image data.

    I could use URLLoader to send Binary ByteArray to the server but then I will lose the ability to have a progress event during the upload, which is not great.

    From what I understand, fileReference.data is set by fileReference.load(). Is there a way to override this function to sort of ‘reload’ a new image ?
    Or maybe modify the constructor of the class to be able to pass a bitmapData object when creating a new object?

    Thanks

  39. JimO says:

    Thanks for this helpful example. I have an app setup to build and run in both in AIR 1.5.3 and Flash 10.0. (The common code is built in a library SWC and included into both apps.)

    Unfortunately, I do not see the complete event firing in AIR, only in Flash (running in the browser). Any idea why? I couldn’t find any discussion of this event not working in AIR. I’ve got this code in the common library SWC (which is marked as requiring Flash 10.0).

  40. saravanan.R says:

    hi
    i use this code in flex but
    i got error in the of (flash.net)
    Could not resolve to a component implementation.
    This above error shown how can i solve

  41. Gogs says:

    So I have some very huge files (>3 MB) directly from digital camera. The issue is that images with height > width, get rotated by 90 degrees clockwise.

    This flip doesn’t happen when width>height. Also, it happens only with huge files. For smaller files, the rotation doesn’t happen. Seems like this is a flash bug, ‘coz its happening on my application as well as yours.

  42. Greg says:

    All well and good, but in Air the fileReference objects in fileReferenceList do not fire the complete event when doing fileList[i].load(). Adobe has not taken bug reports on this appropriately.

  43. Anthony says:

    I need to resize the image before saving it to server, say image uploaded size: 4mb, it should be 300kb on server.

    Anyone can help?
    Thanks

  44. marc says:

    Hi Peter,

    Thanks for the code. It works very well with images.
    Should it also work for videos?

    Trying to Filereference.load() an mp4:
    It dispatches the first progressevent bytesloaded = 0, and then nothing…

  45. marc says:

    Sorry, me again. My fault.

    Solution:
    as this post explains clearly http://blog.wrench.com.au/2010/06/16/filereferenceload-keep-it-in-scope/

    FileReference may not be a local variable that you can catch up in listeners via event.target while loading, but it must be a global variable.

    The problem is it fails silently if you do it the wrong way.

  46. Sergii says:

    Help me please …. I need to make such an application

    1. Selecting images from disk without loading the server.
    2. Ability to edit it (increase / decrease proportionally with a slider and drag)
    3.1 Reduction should work in such a way that no gaps in the editable area (the picture should “stick to the edges of the editor). One editor can be 600 * 300.
    3.2 If a picture is trying to get smaller window sizes, it is necessary to increase by 20%. If even then the picture is less – to give a message.
    4. When you drag a picture there should be no gaps.

  47. Marylka says:

    How do I upload it on my server with ColdFusion. The combination of ColdFusion and Flex 4.

    THX

  48. Very useful, thanks for posting!
    Quick correction: there is an asterisk (*) missing online 16 before .gif.

  49. James says:

    Please help me…Image browse and upload but in Flex 3 – image in panel.