About file uploading and downloading 649
imagePane.addEventListener("complete", imageDownloaded);
imagesCb.addEventListener("change", downloadImage);
uploadBtn.addEventListener("click", uploadImage);
/* If the image does not download, the event object's total property will
equal -1. In that case, display a message to the user. */
function imageDownloaded(event:Object):Void {
if (event.total == -1) {
imagePane.contentPath = "Message";
}
}
/* When the user selects an image from the ComboBox, or when the
downloadImage() function is called directly from the
listener.onComplete() method, the downloadImage() function sets the
contentPath of the ScrollPane in order to start downloading the image
to the player. */
function downloadImage(event:Object):Void {
imagePane.contentPath = "http://www.helpexamples.com/flash/file_io/
images/" + imagesCb.value;
}
/* When the user clicks the button, Flash calls the uploadImage()
function, and it opens a file browser dialog box. */
function uploadImage(event:Object):Void {
imageFile.browse([{description: "Image Files", extension:
"*.jpg;*.gif;*.png"}]);
}
This ActionScript code first imports the FileReference class and initializes, positions, and
resizes each of the components on the Stage. Next, a listener object is defined, and three
event handlers are defined:
onSelect, onOpen, and onComplete. The listener object is
then added to a new FileReference object named
imageFile. Next, event listeners are
added to the
imagePane ScrollPane instance, imagesCb ComboBox instance, and
uploadBtn Button instance. Each of the event listener functions is defined in the code
that follows this section of code.
The first function,
imageDownloaded(), checks to see if the amount of total bytes for the
downloaded images is -1, and if so, it sets the
contentPath for the ScrollPane instance to
the movie clip with the linkage identifier of Message, which you created in a previous step.
The second function,
downloadImage(), attempts to download the recently uploaded
image into the ScrollPane instance. When the image has downloaded, the
imageDownloaded() function defined earlier is triggered and checks to see whether the
image successfully downloaded. The final function,
uploadImage(), opens a file browser
dialog box, which filters all JPEG, GIF, and PNG images.
12. Save your changes to the document.