In an earlier example we looked at “Downloading files in Flex using the FileReference class“, but It looks like we haven’t ever looked at file uploads.
The following example shows how you can use the FileReference class’s browse() method to allow users to select and upload a single file to a Web server.

If you want to allow users to upload multiple files at once, you would use the FileReferenceList class instead of FileReference.

Full code after the jump.

View MXML

<?xml version="1.0" encoding="utf-8"?>
<!-- http://blog.flexexamples.com/2007/09/21/uploading-files-in-flex-using-the-filereference-class/ -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
        layout="vertical"
        verticalAlign="middle"
        backgroundColor="white"
        creationComplete="init();">

    <mx:Script>
        <![CDATA[
            private var fileRef:FileReference;

            private const FILE_UPLOAD_URL:String = "http://www.YOUR-WEBSITE-HERE.com/fileref/uploader.cfm";

            private function init():void {
                fileRef = new FileReference();
                fileRef.addEventListener(Event.SELECT, fileRef_select);
                fileRef.addEventListener(ProgressEvent.PROGRESS, fileRef_progress);
                fileRef.addEventListener(Event.COMPLETE, fileRef_complete);
            }

            private function browseAndUpload():void {
                fileRef.browse();
                message.text = "";
            }

            private function fileRef_select(evt:Event):void {
                try {
                    message.text = "size (bytes): " + numberFormatter.format(fileRef.size);
                    fileRef.upload(new URLRequest(FILE_UPLOAD_URL));
                } catch (err:Error) {
                    message.text = "ERROR: zero-byte file";
                }
            }

            private function fileRef_progress(evt:ProgressEvent):void {
                progressBar.visible = true;
            }

            private function fileRef_complete(evt:Event):void {
                message.text += " (complete)";
                progressBar.visible = false;
            }
        ]]>
    </mx:Script>

    <mx:NumberFormatter id="numberFormatter" />

    <mx:Button label="Upload file"
            click="browseAndUpload();" />
    <mx:Label id="message" />
    <mx:ProgressBar id="progressBar"
            indeterminate="true"
            visible="false" />

</mx:Application>

View source

You’ll notice the previous example doesn’t have a SWF or file upload URL. That would be because I don’t want all of you uploading files to my server. :)

In the previous example, I wrapped the call to fileRef.size in a try..catch block. In ActionScript 3.0, Flash Player throws an error if you attempt to get the size of a zero-byte file.

 
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.

145 Responses to Uploading files in Flex using the FileReference class

  1. Adam says:

    Hi, looks like a good example but I am confused about one thing
    in particular. What serverside script are you using to upload the file?
    I noticed this URL “http://www.YOUR-WEBSITE-HERE.com/fileref/uploader.cfm”;
    which I’m guessing is the file to handle the upload? Can you clarify whether
    a serverside script e.g PHP is needed and if so, would you mind posting
    an example. Much appreciated. Love the site by the way, its very useful.

  2. Steve says:
    using System;
    using System.Collections;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Web;
    using System.Web.SessionState;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.HtmlControls;
    using System.Text;
    
    namespace UploadTest
    {
        ///
        /// Summary description for WebForm1.
        ///
        public class WebForm1 : System.Web.UI.Page
        {
            private void Page_Load(object sender, System.EventArgs e)
            {
                string sResult = "OK";
                if(Request.Files.Count > 0)
                {
                    HttpPostedFile httpPostedFile = Request.Files[0];
                    try
                    {
                        string sFilePath = Server.MapPath(httpPostedFile.FileName);
                        httpPostedFile.SaveAs(sFilePath);
                    }
                    catch(Exception ex)
                    {
                        sResult = ex.Message;
                    }
                }
                else
                    sResult = "No file was uploaded.";
    
                Response.ContentType = "text/xml";
                Response.ContentEncoding = Encoding.UTF8;
    
                Response.Write("<testupload><result>" sResult "</result></testupload>");
            }
    
            #region Web Form Designer generated code
            override protected void OnInit(EventArgs e)
            {
                //
                // CODEGEN: This call is required by the ASP.NET Web Form Designer.
                //
                InitializeComponent();
                base.OnInit(e);
            }
    
            ///
            /// Required method for Designer support - do not modify
            /// the contents of this method with the code editor.
            ///
            private void InitializeComponent()
            {
                this.Load  = new System.EventHandler(this.Page_Load);
            }
            #endregion
        }
    }
    
  3. Steve says:

    Woops – sorry I posted before the message was completed.
    The previous code is for .NET

    The line

    Response.Write("" sResult "");
    

    should read

    Response.Write("<testupload><result>" sResult "</result></testupload>");
    

    [Edit: Peter: Thanks Steve! I edited your comment above.]

  4. peterd says:

    Adam,

    Yes, you will need a server-side script that will accept a file and write it to the hard drive (or whatever you want to do with the file). Here’s my test script that I wrote in ColdFusion:

    <cfsilent><cfsetting enablecfoutputonly="true" />
    <cfset req = getHTTPRequestData( )>
    
    <cffile action="UPLOAD" filefield="Filedata" destination="#ExpandPath('.')#" nameconflict="MAKEUNIQUE">
    <cfsavecontent variable="info">
    <html>
    <head></head>
    <body>
    <cfdump label="CFFILE" var="#cffile#">
    <cfdump label="getHTTPRequestData()" var="#req#">
    <cfif IsDefined("FORM")>
        <cfdump label="FORM" var="#FORM#">
    </cfif>
    <cfif IsDefined("URL")>
        <cfdump label="URL" var="#URL#">
    </cfif>
    </body>
    </html>
    </cfsavecontent>
    
    <cffile action="WRITE" file="#ExpandPath('./')##cffile.serverFileName#.dump.html" output="#info#" addnewline="Yes">
    </cfsilent><cfsetting enablecfoutputonly="false" />
    <cfcontent reset="true" />
    <cfoutput>fileName=#CFFILE.serverFile#&fileSize=#CFFILE.fileSize#</cfoutput>
    

    It’s probably quite overkill as it has a bit of debug code in there (it uploads the file and dumps all the file properties to an HTML file so I can see what’s happening).

    If you are using ColdFusion, I believe you can just use the following one line which uploads a file with the header name “Filedata”, and saves it to the same directory as the ColdFusion template:

    <cffile action="upload" filefield="Filedata" destination="#ExpandPath('./')#" nameconflict="OVERWRITE" />
    

    Although the code is really simple and elegant, note that you’d always want to be careful when accepting file uploads. You would want to try and verify that users aren’t uploading executable server-side scripts which they could then call on the server via HTTP. For example, a user could try and upload a PHP script which tries to delete files or databases from your website.

    I’m not a PHP programmer, so I’ll have to leave that for another commenter (or I’m sure there are several solutions on the web if you Google for it). In fact, the Flash documentation does have some sample PHP upload script posted here: “Working with file upload and download“.

    I also found the following article on the Adobe ColdFusion Developer Center, “Multiple file upload with Flex and ColdFusion“.

    Happy Flexing!

    Peter

  5. peterd says:

    Setve,

    Thanks for the .NET solution! That’s outstanding!

    Anybody have a snippet for PHP?

    Peter

  6. Saeed Ashour says:

    Hi ….

    will be great if anyone post php code for uploading !

  7. peterd says:

    Saeed Ashour,

    You can try the PHP code in the Adobe documentation at: http://livedocs.adobe.com/flash/9.0/main/00000320.html

    You may need to tweak the code a bit, as it looks like the code limits the size of upload that will be accepted (max file upload size appears to be 200KB) and it is also checking the file’s type and only allowing certain file types (such as JPEG, GIF and PNG).

    In fact, here’s the code description from the documentation:

    The following code demonstrates file uploads using PHP, and it includes data validation. The script limits the number of uploaded files in the upload directory to 10, ensures that the file is less than 200 KB, and permits only JPEG, GIF, or PNG files to be uploaded and saved to the file system.

    You can also check out this entry in the Adobe Flex Cookbook, “Uploading files from Flex using PHP“.

    Hope that helps,
    Peter

  8. Adam says:

    Saeed Ashour
    said: “great if anyone post php code for uploading !”

    Me three! I have been googling for ages looking for a Flex multi-upload
    example using PHP but most seem to be using ColdFusion which I know
    nothing about unfortunatly, kind of a big ask but would someone mind sending
    me an example? My email is – dyso_au (AT) hotmail.com
    or a link would do :)

  9. Adam says:

    Anyone with a Flex muti-upload example using PHP?
    My email is – dyso_au (at) hotmail.com or a link will do :)

  10. Jimmy says:

    Adam,
    You can try this link for a multi file upload using php
    http://weblog.cahlan.com/2006/12/flex-upload-component.html

    Cheers!

  11. Mark says:

    Hi. This example is great. One question though. Your server generates a response giving the status of the upload from it’s point of view. How is this response accessed from Flex?

    Thanks
    Mark

  12. Mark says:

    I have been trawling for a while looking for how you get the server’s response back. So far the best I have seen is setting an HTTPStatus event handler, like this:

    fileRef.addEventListener(HTTPStatusEvent.HTTP_STATUS, onHTTPStatus);
    

    The handler looks like this:

    private function onHTTPStatus (event : HTTPStatusEvent) : void
    {
        Alert.show ("Error:"   event.status);
    }
    

    If the server returns a HTTP status other that 200, this handler is called. In my PHP server, I do something like this:

    if ($fileexists)
      header("HTTP/1.0 501 file exists");
    else if ($couldnotsave)
      header("HTTP/1.0 502 could not save");
    else
      header("HTTP/1.0 200 all ok");
    

    In actionscript, event.status will only get the status number. i.e. it will get “501″ and not “501 file exists”.

    Note that after the HTTPStatus event, a IOErrorEvent is also issued.

    Mark

  13. Mark says:

    I’m back! The way to get the response is easy (but not documented in the Flex doc from what I can see):

    fileRef.addEventListener(DataEvent.UPLOAD_COMPLETE_DATA, onUploadCompleteData);
    
    private function onUploadCompleteData (event : DataEvent) : void
    {
        Alert.show (event.data);
    }
    

    Data contains whatever was issued, so in my PHP:
    echo “hello”;

    puts “hello” in event.data.

    Hope this saves someone some time.

    Mark

  14. peterd says:

    Mark,

    Good work, you beat me to a response! Correct, the way to grab the server response is by listening for the uploadCompleteData event like you said. It should be documented in the Flex 2.0.1 language reference documentation (click here).

    I’ll undoubtedly cover this in an upcoming example as this is relatively new to Flash Player (added in Flash Player 9.0.28.0, I believe).

    Peter

  15. Mellisa says:

    Hi there, I’ve been looking for a working example for server side written in JSP for upload and download file. Will appreciate anyone who can give me the code.

  16. Anthony says:

    For those of you who want to use Steve’s ASP.NET fileupload in VS 2003 modify these minor errors:

    1. Change this:

    Response.Write(“” sResult “”);

    to this:

    Response.Write(“” sResult “”);

    2. Change this:

    this.Load = new System.EventHandler(this.Page_Load);

    to this:

    this.Load = new System.EventHandler(this.Page_Load);

    For some reason I couldn’t get this to work in VS 2005. Great job Steve for the .net code.

  17. Anthony says:

    Peter, are ” ” (plus signs) disabled?

  18. peterd says:

    Anthony,

    Ha, seemingly. Posting comments have always been kind of buggy in this template (its very AJAX heavy).

    Try escaping the + signs with a backslash.
    Similarly, excape > signs with &gt; and < with &lt;

    Sigh,

    Peter

    (blah, i see hwo hard it is to post the “+” signs. try wrapping everything in a <pre /> tag and cross your fingers.)

  19. jered jeruel says:

    any example of for file upload using JSP and then will display also hash code in Flex??? Thanks.

  20. vonnhugo says:

    for jsp:

    items = upload.parseRequest(request);
    int counter = 0;

    for(FileItem item : items) {
    try {
    File uploadedFile = new File(uploadDir File.separator item.getName());
    item.write(uploadedFile);

    out.println(“” uploadedFile.getAbsolutePath() “”);
    }
    catch(IOException ioe) {
    System.out.println(“Problem copying temp file. ” ioe);
    }

    try {
    MessageDigest md = MessageDigest.getInstance(“MD5″);
    byte[] message = item.getString().getBytes();
    md.update(message);
    byte[] messageDigest = md.digest();

    StringBuffer sb = new StringBuffer();
    for(int i=0; i” sb.toString() “”);
    }
    catch(Exception e) {
    System.out.println(“Unknown hash algorithm ” e);
    }

    counter ;
    }

    %>

    ——————–

    this works with Apache Tomcat 5.5

    an example here: http://www.webtitude.com/uploadToolTest2/Uploader.html

    don’t bother about uploading so much. the script there deletes the file from server after hash code is displayed.

    - vonnhugo (a.k.a. kris) with rey’s help for the JSP :)

  21. vonnhugo says:

    yikes… i forgot that codes will not show well here. but the idea is there. email me (vonnhugo[at]hotmail.com) if you need these craps. :D

    Update: Here’s the code:

    <%@page import="java.io.IOException"%>
    <%@page import="java.io.File"%>
    <%@page import="java.io.InputStream"%>
    <%@page import="java.io.FileInputStream"%>
    <%@page import="java.security.MessageDigest"%>
    <%@page import="org.apache.commons.fileupload.FileItem"%>
    <%@page import="java.util.List"%>
    <%@page import="org.apache.commons.fileupload.servlet.ServletFileUpload"%>
    <%@page import="org.apache.commons.fileupload.disk.DiskFileItemFactory"%>
    <%@page import="org.apache.commons.fileupload.FileUpload"%>
    
    <?xml version="1.0"?>
    <myUpload>
    
    <%
    
    String uploadDir = pageContext.getServletContext().getRealPath("uploads");
    
    File dir = new File(uploadDir);
    if(!dir.exists()) {
        dir.mkdir();
    }
    
    DiskFileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    
    @SuppressWarnings("unchecked")
    List<FileItem> items = upload.parseRequest(request);
    int counter = 0;
    
    for(FileItem item : items) {
    
        File uploadedFile = new File(uploadDir + File.separator + item.getName());
    
        try {
            item.write(uploadedFile);
    
            out.println("<file"+ counter +">"+ uploadedFile.getAbsolutePath() +"</file"+ counter +">");
        }
        catch(IOException ioe) {
            System.out.println("Problem copying temp file. " + ioe);
        }
    
        InputStream is = null;
    
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
    
            //byte[] message = item.getString().getBytes();
            //md.update(message);
    
            byte[] buffer = new byte[1024];
            is = new FileInputStream(uploadedFile);
            int read = 0;
    
            while( (read = is.read(buffer)) > 0) {
                md.update(buffer, 0, read);
            }
    
            byte[] messageDigest = md.digest();
    
            StringBuffer sb = new StringBuffer();
            for(int i=0; i<messageDigest.length; i++) {
                sb.append(Integer.toHexString( (int)(messageDigest[i] & 0xff)  ));
            }
    
            out.println("<md5hash"+ counter +">"+  sb.toString() +"</md5hash"+ counter +">");
        }
        catch(Exception e) {
            System.out.println("Unknown hash algorithm " + e);
        }
        finally {
            if(is != null) {
                is.close();
            }
        }
    
        counter++;
    }
    
    %>
    
    </myUpload>
    
  22. Rockman says:

    Anyone have problems using multiple uploads with a Windows box? I have a great upload that works great on any mac computer but IO_ERROR on any windows box…

    BTW, I am using the Adobe example scripts and trapping for IO_Error, i think it resutls in #2038..

    any insight would be great , thanks

  23. pankaj says:

    i think it’s a problem of rights to file or directory from/to where we want to Download/Upload

  24. Abhishek says:

    could u tell me how to upload files on server from flex to Ruby on Rails ?

  25. Mukesh Sahu says:

    Hello abhishek
    even i am looking for the same thing.
    i am using RoR as back-end in my flex project.
    Please anyone guide me regarding ruby code for uploading the files.
    thanks in advance.

  26. Paul says:

    What happens if you want to upload (import might be a better term) a file into a client side component such as an RichTextEditor box? The user would then be able to edit the file, and either save it or send it to the server.

    Anyone know how to do this preferably without a server roundtrip.

  27. asha says:

    hi! i just want to know how to upload a file on server using flex2.
    please send reply to this mail as soon as poosible….

  28. peterd says:

    asha,

    Check out the FileReference class (http://livedocs.adobe.com/flex/201/langref/flash/net/FileReference.html), or more specifically, the FileReference class’s upload() method.

    Peter

  29. Muzzammil says:

    i am using backend as java,can anyone post the server side code for image uploading in java which uses this code in the client side

  30. rconceiver says:

    is there any way to get the absolutepath in flex?

  31. peterd says:

    rconceiver,

    No.

    Peter

  32. epox says:

    Hello! i’m trying to upload files to .net with c#, but i’m a newbie with .net, in what kind of file do i put that snippet from steve???, and how do i call it??? thanks!

  33. Alain says:

    Hello,
    I don’t think Paul’s question was answered and my questions goes in a similar direction.
    Is there a way to get the image data from the FileReference object? Or is there another objet that would allow me to?

    The reason is, I would like to covert the image data to a bitearray and send it with other information to AMFPHP as a remote Object.

    I’ve been looking around for an example or tutorial that would come close to this but I can’t find one that actually show how to get the user to load (import) the image in my flex app. from a filebrowser like component.

    Any help would be greatly appreciated.
    Thanks
    -Alain

  34. peterd says:

    Paul,

    I don’t think this is possible without a server round-trip. You’d have to get the user to select a file on their computer, upload that file to a webserver using ColdFusion, PHP, ASP, Java, etc, then download the file and display it in the RichTextEditor control. Then, to save the file locally you would probably would need to send the contents of the RichTextEditor to a server and call FileReference again to save the file. The Flash Player does not allow direct file access from an online Flex application to the user’s hard drive for editing and saving files directly. If you were building a desktop application, you could do this in AIR though.

    Alain,

    Similarly, you’d have to use the FileReference object to have the user select a file from their operating system. Next, you would need to upload the file to a server to save the file and then redownload the image and get the image data that way (for the same reasons as above, Flash Player doesn’t allow for immediate data access without sending the data to the server).

    You may want to ask the same question on a high traffic list like FlexCoders and see if anybody else has any clever solutions or workarounds.

    Peter

  35. Alain says:

    Thank you for the quick response Peter. I will try your suggestion about the FlexCoders list.
    You have a great site by the way. Keep up the good work!

    -Alain

  36. io error 2038 on Tomcat 5.5 on Linux says:

    Can any one help me out with file uploading. I have written a MXML to upload the file using file reference object. This calls the JSP to upload the file. This seems to work on windows for tomcat 5.5

    If i do the same thing on linux I am getting io error 2038. Dont seem to understand the reason for it cause the windows and linux tomcat configuration is the same.

    Please advise !!!!

  37. peterd says:

    io error 2038 on Tomcat 5.5 on Linux,

    Can you file a bug at https://bugs.adobe.com/flashplayer/ and include a simple test case.

    Peter

  38. Fernando Escobar says:

    Hey guys. I’m trying to upload files using JSP as a server-side upload handler, and I really appreciate the contribution on how to do it with JSP.
    But I’m having a problem, every time I try to upload something the browser keeps telling me about the error#2038 I/O error, and I’ve tried with Explorer and FIrefox and still nothing.
    I’ve read a lot about why this could be happening and it seems that the server I’m running this (which is Tomcat) has a mod_security enabled option. So please I’m begging for help, I don’t know what to do. Is there a way to disable mod_security in Tomcat? Or is it something else the problem with the error code #2038?
    Thanks in advance for any replies.

  39. iCao says:

    The FileReferene.upload doesn’t work !!! It work only if you use IE on windows, in any other Case nothing append (no error )

    https://bugs.adobe.com/jira/browse/FP-78

  40. Is their a fix? says:

    Hi all,

    I have a problem uploading files from Mac OSX using a similar method.

    All is fine on Windows on any browser.
    All is fine on OSX as long as my files that I want to upload don’t have spaces in the name.

    Does anyone know how to get round this problem?

    Or do I have to check the filename the user wants to upload and if it has spaces in tell them to rename the files because Adobe can’t get their act together!

    Also are any other characters illegal in the filename only on OSX but I hear the same problems on linux also.

  41. Nitish Dhar says:

    Actually i have designed a flex page . Now i want to have a browse button on the page which takes the path of an image to be uploaded from my local disk and when i click upload it displays it on the same flex page(may be in a text area) . Plz help??

  42. G.vinay kumar says:

    In the above example if i have a SWF or file upload URL and that to i want to upload files in my server only
    will u plzzz reply with that code
    waiting for u r reply

    thanks and regrads
    G.vinay kumar
    Ghoom solutions
    Hyderabad

  43. Sam says:

    Hi. What would i have to do if i wanted to upload it to a directory in my local drive.
    What would i put in place of
    private const FILE_UPLOAD_URL:String = “http://www.YOUR-WEBSITE-HERE.com/fileref/uploader.cfm”;

  44. Sam says:

    And one more thing. Where does it get stored. What exactly is stored in the .cfm file.

  45. Sam says:

    i uploaded it to a remote server here is the link
    http://free.calypsohosting.com/sam2214/testUpload.html

  46. Sam says:

    When it displays completed. Where is it stored?

  47. peterd says:

    Sam,

    I believe you can only upload files to a web server, not your local drive (unless of course your local computer had a web server installed and running).

    You can see the contents of the .CFM file in a previous comment; http://blog.flexexamples.com/2007/09/21/uploading-files-in-flex-using-the-filereference-class/#comment-2777

    And when it displays “completed”, the file would be stored wherever you specified in the <CFFILE /> tag.

    Peter

  48. Dan says:

    Peter this was a great article.

    I was wondering how to go about taking this a step further and writing to a XML file after each upload.

    Just basic information like name, extension, type etc. I know how to access all that, but what I’ve written for the actual writing of the XML file part seems to slip up. I know how to read from an XML file into flex, but writing out to one is giving me the issue. Any ideas/help?

    Thanks

  49. Dan says:

    Decided to go with server side XML file writing. ;) Works like a charm

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">

Anti-Spam Protection by WP-SpamFree