Using for the FileReference class’s uploadCompleteData event to capture data from a server-side script

The previous example, “Using the URLVariables and FileReference classes to pass data from Flex to a server-side script”, showed how you could use the upload() method in the FileReference class along with the URLRequest and URLVariables classes to send data from your Flex application to a server-side script. Well, what happens if you want to send data from your server-side script back to your Flex application? Say hello to the uploadCompleteData event! This event gets dispatched after data is received from the server after a successful upload.

The uploadCompleteData event is not dispatched if data is not returned from the server.

The following example shows how you can set up an event listener for the uploadCompleteData event to display information about the file upload.

Full code after the jump.

View MXML

<?xml version="1.0" encoding="utf-8"?>
<!-- http://blog.flexexamples.com/2007/10/30/using-for-the-filereference-classs-uploadcompletedata-event-to-capture-data-from-a-server-side-script/ -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
        layout="vertical"
        verticalAlign="middle"
        backgroundColor="white"
        creationComplete="init();">

    <mx:Script>
        <![CDATA[
            import flash.net.FileReference;
            import mx.controls.Alert;
            import mx.utils.StringUtil;

            private var fileRef:FileReference;
            private var urlReq:URLRequest;

            private function init():void {
                fileRef = new FileReference();
                fileRef.addEventListener(Event.SELECT, fileRef_select);
                fileRef.addEventListener(Event.COMPLETE, fileRef_complete);
                fileRef.addEventListener(IOErrorEvent.IO_ERROR, fileRef_ioError);
                fileRef.addEventListener(DataEvent.UPLOAD_COMPLETE_DATA, fileRef_uploadCompleteData);

                urlReq = new URLRequest();
                urlReq.url = "http://localhost:8300/fileref/uploader.cfm";
            }

            private function fileRef_uploadCompleteData(evt:DataEvent):void {
                var strData:String = StringUtil.trim(evt.data);
                var vars:URLVariables = new URLVariables(strData);
                Alert.show(vars.fileName, "fileName");
            }

            private function start():void {
                fileRef.browse();
            }

            private function fileRef_select(evt:Event):void {
                fileRef.upload(urlReq);
            }

            private function fileRef_complete(evt:Event):void {
                Alert.show(evt.toString(), evt.type);
            }

            private function fileRef_ioError(evt:IOErrorEvent):void {
                Alert.show(evt.text, evt.type);
            }
        ]]>
    </mx:Script>

    <mx:Button label="upload" click="start();" />

</mx:Application>

View source

The previous example just uploads to http://localhost/ (in my case my local JRun server). Since that is pretty much useless 99.8% of the time, you would need to change that URL to your ColdFusion/PHP/ASP/Java upload script on your own server.

If you’re a ColdFusion’er, you can see my upload script in the previous entry, “Using the URLVariables and FileReference classes to pass data from Flex to a server-side script”. Note that the script has the following lines, which return some name/value pairs to our Flex application. Flex will receive the data as a string, but you can easily convert the string into a URLVariables object by passing the string to the URLVariables constructor, or by using the URLVariables class’s decode() method. Once converted, Flex will have access to two variables from the ColdFusion script, fileName and fileSize. The fileName variable contains the name of the uploaded file from the server. Since the ColdFusion <cffile /> tag used a nameConflict attribute of “MAKEUNIQUE”, the server will generate a unique file name if a file by that name already exists in the specified directory. The fileSize variable contains the sie of the upload file from the server. Also, note that unlike ActionScript, ColdFusion is not case sensitive.

<cfoutput>fileName=#CFFILE.serverFile#&fileSize=#CFFILE.fileSize#</cfoutput>

11 thoughts on “Using for the FileReference class’s uploadCompleteData event to capture data from a server-side script

  1. como hago el filtrado de un cfgrid como este
    function applyFilter( term:String, grid:mx.controls.DataGrid, columns:Array ):Void {

    var filterTerm:String = term.toString().toLowerCase();

    if(filterTerm.length > 0) {
    if(_global.unfilteredData[grid.id] == undefined){
    if (_global.unfilteredData == undefined){
    _global.unfilteredData = {};
    }
    _global.unfilteredData[grid.id] = grid.dataProvider.slice(0);
    }

    var filteredData:Array = [];

    for(var i = 0; i

  2. <?php
    //also change user name variable in count.php
    $user="xyz";
    //create the directory if doesn't exists (should have write permissons)
    if(!is_dir("files/".$user."/")) mkdir("files/".$user."/", 0755);
    //move the uploaded file
    move_uploaded_file($_FILES['Filedata']['tmp_name'], "files/".$user."/".$_FILES['Filedata']['name']);
    chmod("files/".$user."/".$_FILES['Filedata']['name'], 0777);
    ?>
    
  3. Peter,

    When I run your code I get an error:

    Error: Error #2101: The String passed to URLVariables.decode() must be a URL-encoded query string containing name/value pairs.

    Any ideas why?

    Thx.

  4. i was using asp.net server side and actionscript 3.0 client side
    trying to upload file(s) , when i use POST method i dont see values coming, changed to GET working.

    thanks,
    venkat

  5. Hello,

    I am trying to upload files using Flex 3.0 and Java.
    Can anyone help me out with the code?

    Thanks in Advance,
    Sunil.

  6. Peter,
    I’m trying to modify this sample to work with multiple files by using FileReferenceList, a for loop, and the ColdFusion uploader file from your previous example. Everything works OK with the exception of the uploadCompleteData event. I’m not getting anything at all. It doesn’t even fire. I’ve tried changing the event to fire based on the list of files as well as the individual file as it is uploaded, but no luck. I’m not in front of my work machine right now, so don’t have access to the file I wrote, but if you want to see what I am doing, I’d be happy to upload it for you. Do you have any ideas as to what I am doing wrong? Thanks in advance.
    mm

    1. I figured it out. I had a datagrid on the page that displayed the items I selected for downloading. That datagrid used an arraycollection as the dataprovider. When I changed the upload actionscript to look at the individual entries as filereferences rather than objects in an arraycollection, the event started firing correctly. Thanks again. Love all the information on your blog.

Comments are closed.