Monday, February 28, 2011

File handling with AS 3.0

In this article we are going to play with local files and it’s contents.
We are going to see how to access these files from browser containing flash movie with and with out use of server side scripting (Here consider PHP as server side scripting).

From many years, Flash proved itself and make his own place on web browser.
For advertising , games ,banners etc. as the days gone Flash reached to next level with improvement in OOP techniques ‘Action Script 3.0’. Now it becomes so powerful that it can make Online Editors, Tools, Web sites, and many more things.
Some times user need to access their own files stored on their machine.
Lets see how to use their files.
In the following examples I played with Image files which is same as text files, audio files, video files. Just difference is while using contents of file you need to type cast it some where.

Single local file Uploading with help of PHP. 
Here is Action Script 3.0 code for single file uploading.
Focus of this article is how to use local files data and main advantage of file uploading is you can use that local file any where any time on browser because its now on server.
Ill explain code line by line.

var fileRef:FileReference
/*we need a file reference (consider file pointer) to connect with local file*/
var fileName="xyz.abc"
/*This is name of file we are going to store on server. Its good to be known already as we need it while accessing the uploaded file in server*/
UploadBtn.addEventListener(MouseEvent.CLICK,AddFile);
function AddFile(_e:MouseEvent):void
{
                fileRef= new FileReference();
/*Here instance for file reference is created */
                var _FileFilter:FileFilter=new FileFilter("Images (*.jpg, *.jpeg, *.gif, *.png)","*.jpg;*.jpeg;*.gif;*.png");
/*File Filter is used to validate which file types are only accessible to user*/
                fileRef.addEventListener(Event.SELECT, FileSelectHandler);
/* Flash dispatches this event when user select file from browse window*/
                fileRef.addEventListener(IOErrorEvent.IO_ERROR, FileIOErrorHandler);
/* Flash dispatches this event if accessing selected file has error */
                 fileRef.addEventListener(ProgressEvent.PROGRESS, FileProgressHandler);
/* Flash dispatches this event while uploading file. It gives information about progress of uploading*/
                fileRef.browse([_FileFilter]);
/* Browse window box opens */
}
function FileProgressHandler(e:ProgressEvent):void
{
                var file:FileReference = FileReference(e.target);
                trace("File Progress name=" + file.name + " bytesLoaded=" + e.bytesLoaded + " bytesTotal=" + e.bytesTotal);
}
/* ProgressEvent gives detailed information about file which is uploading */

function FileIOErrorHandler(e:IOErrorEvent):void
{
                trace("File Error: " + e);
}
/* IOErrorEvent gives Error about file if there is Error in uploading */

function FileSelectHandler(event:Event):void
{
        var file:FileReference;
        file = FileReference(event.target);
/*Here we assign file FileReference for currently selected file*/
        fileName=file.name
/*We get file name with extension using name property. We never get full path of local file.*/
        file.addEventListener(Event.COMPLETE, completeFileUploadHandler);
        file.addEventListener(IOErrorEvent.IO_ERROR, FileIOErrorHandler);
        file.addEventListener(ProgressEvent.PROGRESS, FileProgressHandler);
var request:URLRequest = new URLRequest("http://www.mysite/uploadFile.php?fName="+ fileName );                   file.upload(request);
}
/*Here all the data is send to uploadFile.php file. */
function completeFileUploadHandler(e:Event):void

{
Trace(“File uploaded.”)
}
Once file is uploaded and you know exact path of file, You can use it in your Flash project as,
var request:URLRequest = new URLRequest("http://www.mysite/FileGodown/"+ fileName);
var ImageLoader:Loader=new Loader();
ImageLoader.load(request);
ImageLoader.contentLoaderInfo.addEventListener(Event.COMPLETE,ImageDownloading);
function ImageDownloading(e:Event):void
{
                addChild(e.target.loader.content);
}


Multiple local file Uploading with help of PHP.
Now lets see How to upload multiple files at the same time.
Advantage of multiple file uploading is, you do not need to open browse window each time to upload file. But while using these files be careful about sequence of uploading.
The difference between Multiple file uploading and Single file uploading is FileReferenceList.
Lets see ActionScript 3.0 Code,

var fileRef:FileReferenceList
/*It is a list of file references consider as list of pointers for each file selected. */
var totalFiles:Number=0;
/*Variable to store no of files selected*/
var currentFile:Number=0;
/*Variable which tells current no of file downloading */
var filenameArray:Array;
/*Array to store path of files uploaded. So that we can use it later.*/
UploadBtn.addEventListener(MouseEvent.CLICK,AddFile);
function AddFile(_e:MouseEvent):void
{
                fileRef= new FileReferenceList();
/*For multiple file uploading we need to use FileReferenceList insted of FileReference */
                var _FileFilter:FileFilter=new FileFilter("Images (*.jpg, *.jpeg, *.gif, *.png)","*.jpg;*.jpeg;*.gif;*.png");
                fileRef.addEventListener(Event.SELECT, FileSelectHandler);
                fileRef.addEventListener(IOErrorEvent.IO_ERROR, FileIOErrorHandler);
    fileRef.addEventListener(ProgressEvent.PROGRESS, FileProgressHandler);
                fileRef.browse([_FileFilter]);
}
function FileProgressHandler(e:ProgressEvent):void
{
                var file:FileReference = FileReference(e.target);
                trace("File Progress name=" + file.name + " bytesLoaded=" + e.bytesLoaded + " bytesTotal=" + e.bytesTotal);
}
function FileIOErrorHandler(e:IOErrorEvent):void
{
                trace("File Error: " + e);
}
function FileSelectHandler(event:Event):void
{
                var file:FileReference;
/*file is FileReference used to assign FileReference in FileReferenceList */
    var selectedFileArray:Array = (FileReferenceList(event.target)).fileList;
/*For use of simplicity we convert FileReferenceList into Array.*/
                totalFiles=selectedFileArray.length;
/*Length of Array is no of files Selected for uploading.*/
filenameArray=new Array();
for (var i:uint = 0; i < selectedFileArray.length; i++)
    {
        file = FileReference(selectedFileArray[i]);
        file.addEventListener(Event.COMPLETE, completeFileUploadHandler);
        filenameArray[i]=file.name;
/*File name of current file is stored in Array.*/
var request:URLRequest = new URLRequest("http://www.mysite/uploadFile.php?fName="+filenameArray[i]);                              
 file.upload(request);
/*Current file is send to uploadFile.php  file with file name.*/
    }
}
function completeFileUploadHandler(e:Event):void
{
/*As soon as file is uploaded it is ready to use in Flash. We have array of file names and server path. We use it here.*/
var request:URLRequest = new URLRequest ("http://www.mysite/FileGodown/"+filenameArray[currentFile]);
                currentFile++;
                var ImageLoader:Loader=new Loader();
                ImageLoader.load(request);
                ImageLoader.contentLoaderInfo.addEventListener(Event.COMPLETE,ImageDownloading);
}
function ImageDownloading(e:Event):void
{
If(currentFile== totalFiles)
trace(“All files added in flash.”)
addChild(e.target.loader.content);
}


Flash cannot create file or cannot connect to database so we need server side scripting language like PHP.

Here is code for uploadFile.php
<?php
$file = $_GET['fName'];
//$file variable contain name of file to be uploaded.
$finalDir = "FileGodown/";
//server contain “FileGodown” directory where files are stored.
move_uploaded_file($_FILES['Filedata']['tmp_name'], $finalDir.$file);

$directory = opendir($finalDir);
//opens directory for writing new file.
$files = array();
while($file = readdir($directory))
{
    array_push($files, array($finalDir.$file, filectime($finalDir.$file)));
}
print_r($files);
closedir($directory);
//Closes directory for writing new file.
?>


Check out this article in FFD Magazine March  Issue.

No comments:

Post a Comment