Wo wo wooo
Here we are with a new article to add to the series on how to load external files with Flash CS3.
We saw how to
communicate with a PHP file and
how to integrate PHP and mySQL to Flash CS3
Now we will see how to load an external text file and display it in Flash CS3.
I would like to precise that this article is only educative and that I stick to the idea that to load external data, the best way is using an XML file.
Anyway…let us get into it… I create a FLA and save it as ‘file_di_testo.fla’.
I create a Document Class, an AS file saved as ‘Main.as’, implemented the following way:
Code:
package
{
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.IEventDispatcher;
import flash.net.URLLoader;
import flash.net.URLVariables;
import flash.net.URLRequest;
public class Main extends MovieClip
{
public function Main()
{
inviaDati();
}
private function addListeners(d:IEventDispatcher):void
{
d.addEventListener(Event.COMPLETE,completato);
}
private function completato(e:Event):void
{
var loader:URLLoader=URLLoader(e.target);
var vars:URLVariables=new URLVariables(loader.data);
trace(vars.nome);
}
private function inviaDati():void
{
var richiesta:URLRequest=new URLRequest();
richiesta.url='http://www.flepstudio.org/swf/pippo.txt';
var loader:URLLoader=new URLLoader();
addListeners(loader);
try
{
loader.load(richiesta);
}
catch (error:Error)
{
trace('Non è stato possibile caricare il documento');
}
}
}
}
The text file is named as ‘pippo.txt’, into which I have this simple declaration:
nome=filippo
Let us analyse the code
Constructor function
public function Main()
{
I call the method inviaDati();
inviaDati();
}
Methods
inviaDati();
I ask Flash to do an URL request using the URLRequest Class
var richiesta:URLRequest=new URLRequest();
I assign the path to the text file as the property of the URL request
richiesta.url='http://www.flepstudio.org/swf/pippo.txt';
I create an URLLoader
var loader:URLLoader=new URLLoader();
I call the method addListeners and load the text file using the method load of the Loader Class.
If the call to the file is incorrect, I do a trace which returns a message of error
addListeners(loader);
try
{
loader.load(richiesta);
}
catch (error:Error)
{
trace('Non è stato possibile caricare il documento');
}
addListeners();
I add a listener to follow the file’s loading phase. In this case, we only need it to know when the file has been loaded completely
d.addEventListener(Event.COMPLETE,completato);
completato();
I create a Loader to be able to retrieve the data from the uploaded file. In fact, I pass as a parameter the first URLLoader which has done the call
var loader:URLLoader=URLLoader(e.target);
I create an instance of the URLVariables Class to which I pass as parameter the data of the new URLLoader
var vars:URLVariables=new URLVariables(loader.data);
I retrieve the data, calling ‘nome’ (name of the variable included in the text file) as a property of URLVariables
trace(vars.nome);
Stay tuned !