Monday, February 28, 2011

Loading local file data through byte array without uploading to Server

Here we will see how to use local files data in Flash. You can use any type of file but remember to convert it into proper data type. We are going to use ByteArray here.
var fileRef:FileReference=new FileReference();
var fileFilter:FileFilter=new FileFilter("Images: (*.jpeg, *.jpg, *.gif, *.png)", "*.jpeg;*.jpg;*.gif;*.png");
var bytArr:ByteArray

fileRef.browse([fileFilter])
fileRef.addEventListener(Event.SELECT,select);
function select(e:Event)
{
fileRef.load()
/*We are going to load selected files data*/
fileRef.addEventListener(Event.COMPLETE,loadComplete);
}

function loadComplete(e:Event)
{
                bytArr=e.target.data
/*When load is completed. We will convert it into ByteArray.*/
                var ldr:Loader=new Loader()
                ldr.contentLoaderInfo.addEventListener(Event.COMPLETE,addImage)
                ldr.loadBytes(bytArr);
/*As we have now local files data, we can use it as we want. Here I am going to load that ByteArray. As it is an Image I used loadBytes method of loader. If data is text u can directly insert that text into any text box. Same like sound. If local file is sound file you can directly play it once you converted it into Byte Array.*/
}
function addImage(e:Event)
{
                addChild(e.target.loader.content)
}

Lets see example how to load image and save same image in local disk.
var fileRef:FileReference=new FileReference();
var fileFil:FileFilter=new FileFilter("Images: (*.jpeg, *.jpg, *.gif, *.png)", "*.jpeg;*.jpg;*.gif;*.png");
var bytArr:ByteArray
var saveFil:FileReference=new FileReference()
/*We took another FileReference  to save file.*/
fileRef.browse([fileFil])
fileRef.addEventListener(Event.SELECT,select);
function select(e:Event)
{
fileRef.load()
fileRef.addEventListener(Event.COMPLETE,comp);
}

function comp(e:Event)
{
                bytArr=e.target.data
/*When load is completed. We will convert it into ByteArray.*/
                saveFil.save(bytArr)
/*FileReference.save() method will ask you location and name of file*/

You can see this article in FFD Magazine March issue.
}

Downloading file to local disk from server.

This method is quite simple to download any file from server.
navigateToURL(new URLRequest("http://www.mysite/FileGodown/abc.zip"));
or
navigateToURL(new URLRequest("http://www.mysite/FileGodown/abc.jpg"));
/*Browser will ask you for save or open file.*/

Another method is
var _file:FileReference=new FileReference();
 _file.addEventListener(Event.COMPLETE, ImageDownloading);
_file.addEventListener(IOErrorEvent.IO_ERROR, FileIOErrorHandler);
var request:URLRequest = new URLRequest(“http://www.mysite/FileGodown/abc.jpg”);
_file.download(request,fileName)
}

function ImageDownloading(e:Event):void
{
trace(“File downloaded.”)
}
/*Here you will get proper save window to save file. */

You can see this article in FFD Magazine March issue.

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.

Experiencing JSON with Flash AS 3.0.


Hello friends,
Main thing about JSON is IT’S NOT WELL KNOWN.
Now  its time to know about it.

What you will learn..
JSON and its structure.
Actual use of JSON in Flash Projects.
Advantage over XML

What you should know..
XML, its structure and use.

What is JSON
JSON is JavaScript Object Notation a light weight data exchange format based on JavaScript Language.
It is a simple text format which is language independent and easy to use for many languages as ASP, PHP, ActionScript, C ,C++, Java, Ruby, Pearl and many more…

Structure of json
Objects:  Objects begin with opening curly braces “{” and end with closing  curly braces ”}”.
Ex. {Object}
Object members: Object Members consist of strings and values, separated by colon (:).
Members are separated by commas.
Ex.
 {
“Name”:”Chinu”,
“Contact”:1234567890
}
Arrays: Arrays begin with “[” braces and end with “]” braces and contain values which are separated by commas. Value can be a string, a number, an object, an array, or Boolean value or null.
Strings: Strings are surrounded by double quotes.
A simple example of JSON:
{
  "Employee": {
    "Name":”Chinu”,
    "Eid":151,
    "Designation":"Developer",
    "Address":
    {
      "City":"Pune",
      "Country": “India”,
      "Pin": 100100
    },
  "WorkArea":[“Design” , ”Development” , ”Testing”]
  }
}
Here,
 Employee is a top-level object; all other data is a member of that object. Name, Eid and Designation are all simple members of Employee Object having number and string data. Address is a nested object, having members as City , Country, Pin. WorkArea is also simple member of Employee which is an array, containing String values.

Comparing with xml
As compare to XML, JSON is very easy to use and read/write for human and machine as it contain less grammar/syntax.
JSON does not use [CDATA[]] feature to represent html data.
XML is document oriented Markup Language so it is better to use as document exchange format,
JSON is data oriented language so better to use as data exchange format.
XML is adopted by industry as it is widely known than JSON.
There are lot of advantages of JSON over XML regarding Data types supports, memory management, browser security, faster execution, data serialization/ deserialization etc.
Many web services(like Google, yahoo, flickr etc) use JSON instead of XML.
JSON ex.
{
“Employee”:{
“Name”:”Chinu”,
“Eid”:101,
“Add”:{
“City”:”Pune”,
“Country”:”India”
}
}
}
Same JSON Ex. In simple XML format is represented as,
<?xml version="1.0" ?>
<EmpDetails>
< Employee >
<Name>Chinu</Name>
<Eid>101</Eid>
<Add>
<City>Pune</City>
<Country>India</Country>
</Add>
</ Employee >
</ EmpDetails >
 

JSON with  ActionScript
JSON is very useful in flash projects. As per my experience , I use it in php where I used to create dynamic XML. But while loading thousands clip arts I need to wait for some time to parse and traverse XML for my Flash Design Tool.
Here is simple example as,
Here is my ActionScript Code as,
import com.adobe.serialization.json.JSON;
var urlldr:URLLoader=new URLLoader();
urlldr.load(new URLRequest('sample.txt'));
urlldr.addEventListener(Event.COMPLETE,jsonload);
function jsonload(e:Event):void
{
                var JSONData:Array = JSON.decode(e.target.data);
                for(var i=0;i< JSONData.length;i++)
                trace(JSONData [i].number);
}


Out put is,
12345
67890

sample.txt file contain data as,
 [ {"name":"Sachin", "number":"12345"}, {"name":"Vidya", "number":"67890"}]
Once I loaded simple.txt file I got data in that file.
Then I decode all text to JSON format, here data is validate.
Then all JSON data is collected in an Array for later use.
You can encode any JSON object as String.
var myString:String = JSON.encode( myValue );
 
other pretty thing I found is you can direct compare two JSON objects as,
see below function 
 
function compareObj (obj1:Object, obj2:Object): Boolean {
      try {
               var value1: String = JSON.encode(obj1);
               var value2: String = JSON.encode(obj2);
      }
      catch (e:JSONParseError) {
               trace('Error : '+ e.text);
               return false;
      }
      return (value1 === value2);
  }
 
It is very difficult to compare two XMLs or its nodes.

Lets Spread JSON.

Here are some useful links:
JSON validator
JSON home
JSON library for ActionScript
https://github.com/mikechambers/as3corelib/

Check out this article in FFD Magazine February  Issue.