ActionScript
Flash AS3: Using FileReference And PHP To Upload Files To Server
June 9, 2010
0

FileReference.upload() function is a handy addition to Flash. In conjunction with server-side language, it can be used to upload files to the server or to a database. In this example, we will use a PHP script to retrieve the file data and save the file onto the server.

Outline:

  • Call FileReference.browse() in response to a user action (such as clicking a button).
  • Listen to Event.SELECT, which indicates thet the user has selected a file.
  • Call FileReference.load() to load the file.
  • Listen to Event.COMPLETE, which indicates thet the file is uploaded (in Flash) and ready to send to the server.
  • Call FileReference.upload() to upload the file.
  • Listen to DataEvent.UPLOAD_COMPLETE_DATA, which indicates that the upload (to server) is complete.Example:
    // www.permadi.com
    
    import flash.events.MouseEvent;
    import flash.net.FileReference;
    import flash.net.FileFilter;
    import flash.utils.ByteArray;
    import flash.events.MouseEvent;
    import flash.events.Event;
    import flash.events.IOErrorEvent;
    import flash.display.MovieClip;
    import fl.controls.ProgressBarMode;
    
    var mFileReference:FileReference;
    
    // Setup button to handle browsing
    browseButton.buttonMode=true;
    browseButton.mouseChildren=false;
    browseButton.addEventListener(MouseEvent.CLICK, onBrowseButtonClicked);
    // Hide progress bar
    progressBar.visible=false;
    
    // This function is called when the BROWSE button is clicked.
    function onBrowseButtonClicked(event:MouseEvent):void
    {
    	trace("onBrowse");
    	mFileReference=new FileReference();
    	mFileReference.addEventListener(Event.SELECT, onFileSelected);
    	var swfTypeFilter:FileFilter = new FileFilter("SWF/JPG/PNG Files","*.jpeg; *.jpg;*.gif;*.png");
    	var allTypeFilter:FileFilter = new FileFilter("All Files (*.*)","*.*");
    	mFileReference.browse([swfTypeFilter, allTypeFilter]);
    }
    
    // This function is called after user selected a file in the file browser dialog.
    function onFileSelected(event:Event):void
    {
    	trace("onFileSelected");
    	// This callback will be called when the file is uploaded and ready to use
    	mFileReference.addEventListener(Event.COMPLETE, onFileLoaded);
    
    	// This callback will be called if there's error during uploading
    	mFileReference.addEventListener(IOErrorEvent.IO_ERROR, onFileLoadError);
    
    	// Optional callback to track progress of uploading
    	mFileReference.addEventListener(ProgressEvent.PROGRESS, onProgress);
    
    	// Tells the FileReference to load the file
    	mFileReference.load();
    
    	if (mFileReference.size > 500*1024)
    	{
    		trace("File too big");
    	}
    	// Show progress bar
    	progressBar.visible=true;
    	progressBar.mode=ProgressBarMode.MANUAL;
    	progressBar.minimum=0;
    	progressBar.maximum=100;
    }
    
    // This function is called to notify us of the uploading progress
    function onProgress(event:ProgressEvent):void
    {
    	var percentLoaded:Number=event.bytesLoaded/event.bytesTotal*100;
    	trace("loaded: "+percentLoaded+"%");
    	progressBar.setProgress(percentLoaded, 100);
    }
    
    // This function is called after the file has been uploaded.
    function onFileLoaded(event:Event):void
    {
    	var fileReference:FileReference=event.target as FileReference;
    
    	// These steps below are to pass the data as DisplayObject
    	// These steps below are specific to this example.
    	var data:ByteArray=fileReference["data"];
    	trace("File loaded");
    	var movieClipLoader:Loader=new Loader();
    	movieClipLoader.loadBytes(data);
    	movieClipLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, onMovieClipLoaderComplete);
    
    	mFileReference.removeEventListener(Event.COMPLETE, onFileLoaded);
    	mFileReference.removeEventListener(IOErrorEvent.IO_ERROR, onFileLoadError);
    	mFileReference.removeEventListener(ProgressEvent.PROGRESS, onProgress);
    }
    
    function onFileLoadError(event:Event):void
    {
    	// Hide progress bar
    	progressBar.visible=false;
    	mFileReference.removeEventListener(Event.COMPLETE, onFileLoaded);
    	mFileReference.removeEventListener(IOErrorEvent.IO_ERROR, onFileLoadError);
    	mFileReference.removeEventListener(ProgressEvent.PROGRESS, onProgress);
    	browseButton.visible=true;
    	progressBar.visible=false;
    	trace("File load error");
    }
    
    // This function below is specific to this example.
    // It does the processing required to display the swf/png/jpeg file that we have just loaded.
    function onMovieClipLoaderComplete(event:Event):void
    {
    	var loadedContent:DisplayObject=event.target.content;
    	var loader:Loader=event.target.loader as Loader;
    	// Fit to stage
    	trace("loadedContent.width="+loadedContent.width);
    	loadedContent.scaleX=container.width/loadedContent.width;
    	loadedContent.scaleY=container.height/loadedContent.height;
    	trace("loadedContent.scaleX="+loadedContent.scaleX);
    	trace("loadedContent.width="+loadedContent.width);
    	trace("this.stage.width="+this.stage.width);
    	container.addChild(loader);
    
    	var filename:String=mFileReference.name;
    	var urlRequest:URLRequest = new URLRequest("uploadFile.php");
    	urlRequest.method = URLRequestMethod.POST;
    
    	browseButton.visible=false;
    	// Optional callback to track progress of uploading
    	mFileReference.addEventListener(ProgressEvent.PROGRESS, onProgress);
     	mFileReference.addEventListener(DataEvent.UPLOAD_COMPLETE_DATA,onUploadComplete);
    	mFileReference.upload(urlRequest);
    }
    
    function onUploadComplete(event:Event):void
    {
    	// Optional callback to track progress of uploading
    	mFileReference.removeEventListener(ProgressEvent.PROGRESS, onProgress);
    	mFileReference.removeEventListener(DataEvent.UPLOAD_COMPLETE_DATA,onUploadComplete);
    	browseButton.visible=true;
    	progressBar.visible=false;
    }
    
    

    Much of the code above is explained here: https://www.permadi.com/blog/2010/06/flash-as3-using-filereference-to-load-files-example-for-flash-cs4-and-above/. The new additions are code this portion, which calls FileReference.upload().

    var filename:String=mFileReference.name;
    var urlRequest:URLRequest = new URLRequest("uploadFile.php");
    urlRequest.method = URLRequestMethod.POST;
    
    // Optional callback to track progress of uploading
    mFileReference.addEventListener(ProgressEvent.PROGRESS, onProgress);
    mFileReference.addEventListener(DataEvent.UPLOAD_COMPLETE_DATA,onUploadComplete);
    mFileReference.upload(urlRequest);
    

    The code references a php file named uploadFile.php, which is shown below. This uploadFile.php simply copies the file into the same folder.

    <?php
    $uploadPath = basename( $_FILES['Filedata']['name']);
    if (move_uploaded_file($_FILES['Filedata']['tmp_name'], $uploadPath))
    {
         echo "OK";
    }
    else
    {
         echo "ERROR";
    }
    ?>
    

     

    Notes:

    • Make sure the folder where the file is being written to has write permission (this can pose security risk, so beware).
    • There is no checking in the example php script for duplicate filenames.
    • FileReference.size can be used to check the size of the file. This variable is valid after Event.SELECT is fired.