Tag Archive for 'filereference'

16
Jun
10

FileReference.load() - keep it in scope!

Just a quick note (possibly to self) that when dealing with FileReference you need to ensure that the scope of the FileReference is maintained. This was mentioned in the Actionscript documentation, but it took me a while to figure out that that could be the problem for my code failing silently. Originally I thought it was because I wasn’t using the right playerglobal.swc from within Flex, or that I couldn’t export using Flex SDK 3.2 (as this method is a Flash Player 10 one). It took me a while to reread the documentation for the load method and comprehend that perhaps I needed to declare some instance variables instead of local ones. Some code will hopefully illustrate what I mean:

public function uploadImage():void
{
	var __imageTypes:FileFilter = new FileFilter("Images (*.jpg, *.jpeg, *.gif, *.png)", "*.jpg; *.jpeg; *.gif; *.png");
	var __fileRef:FileReference = new FileReference();
	try	{
		__fileRef.addEventListener(Event.SELECT, onFileSelect);
		__fileRef.addEventListener(Event.COMPLETE, onFileOpen);
		__fileRef.browse([__imageTypes]);
	} catch (error:Error) {
		trace("Unable to browse for files.");
	}
}

private function onFileSelect(event:Event):void
{
	trace("onFileSelect called");
	var fileRef:FileReference = event.target as FileReference;
	fileRef.load();
}

private function onFileOpen(event:Event):void
{
	trace("onFileOpen called");
	var fileRef:FileReference = event.target as FileReference;
	var data:ByteArray = fileRef.data as ByteArray;
	var encoder:Base64Encoder = new Base64Encoder();
	encoder.encodeBytes(data);
	trace(encoder.toString())
}

The problem with that code is that the original __fileRef variable is only available within the uploadImage function. As soon as onFileSelect is triggered (which works fine), fileRef (a new local variable within this function) trys to call load(). This was failing silently for me.

So instead of declaring the original __fileRef variable as a local one, I’ve declared it as a private variable in the class. That way it’s always in scope!




Categories

Recent Comments

Posts this month

February 2012
M T W T F S S
« Nov    
 12345
6789101112
13141516171819
20212223242526
272829  

Archives