Flash CS3 Documentation |
|||
| Learning ActionScript 2.0 in Adobe Flash > Working with External Data > About file uploading and downloading > Adding file upload functionality to an application | |||
The following procedure shows you how to build an application that lets you upload image files to a server. The application lets users select an image on their hard disks to upload and then send it to a server. The image that they upload then appears in the SWF file that they used to upload the image.
Following the example that builds the Flash application is an example that details the server-side code. Remember that image files are restricted in size: you can only upload images that are 200K or smaller.
The file that you have tried to download is not on the server.
In the final application, this warning might appear for one of the following reasons, among others:
|
NOTE |
|
The width of the text field should be less than the width of the ScrollPane instance (400 pixels); otherwise users have to scroll horizontally to view the error message |
|
NOTE |
|
The code comments include details about the functionality. A code overview follows this example. |
import flash.net.FileReference;
imagePane.setSize(400, 350);
imagePane.move(75, 25);
uploadBtn.move(75, 390);
uploadBtn.label = "Upload Image";
imageLbl.move(75, 430);
imageLbl.text = "Select Image";
statusLbl.move(210, 390);
statusLbl.text = "Status";
imagesCb.move(75, 450);
statusArea.setSize(250, 100);
statusArea.move(210, 410);
/* The listener object listens for FileReference events. */
var listener:Object = new Object();
/* When the user selects a file, the onSelect() method is called, and passed a reference to the FileReference object. */
listener.onSelect = function(selectedFile:FileReference):Void {
/* Update the TextArea to notify the user that Flash is attempting to upload the image. */
statusArea.text += "Attempting to upload " + selectedFile.name + "\n";
/* Upload the file to the PHP script on the server. */
selectedFile.upload("http://www.helpexamples.com/flash/file_io/uploadFile.php");
};
/* When the file begins to upload, the onOpen() method is called, so notify the user that the file is starting to upload. */
listener.onOpen = function(selectedFile:FileReference):Void {
statusArea.text += "Opening " + selectedFile.name + "\n";
};
/* When the file has uploaded, the onComplete() method is called. */
listener.onComplete = function(selectedFile:FileReference):Void {
/* Notify the user that Flash is starting to download the image. */
statusArea.text += "Downloading " + selectedFile.name + " to player\n";
/* Add the image to the ComboBox component. */
imagesCb.addItem(selectedFile.name);
/* Set the selected index of the ComboBox to that of the most recently added image. */
imagesCb.selectedIndex = imagesCb.length - 1;
/* Call the custom downloadImage() function. */
downloadImage();
};
var imageFile:FileReference = new FileReference();
imageFile.addListener(listener);
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.
If you complete this step, you won't run into security restrictions if you test your document in a local browser.
When you're finished, go on to the next procedure, in which you create the container for the SWF file.
For a sample source file for this example, FileUpload.fla, see the Flash Samples page at www.adobe.com/go/learn_fl_samples. Download the Samples zip file and navigate to the ActionScript2.0/FileUpload folder to access this sample.
The following procedure requires that PHP is installed on your web server and that you have write permissions to subfolders named images and temporary. You need to first complete the previous procedure, or use the finished SWF file available in the previously noted folders.
<?php
$MAXIMUM_FILESIZE = 1024 * 200; // 200KB
$MAXIMUM_FILE_COUNT = 10; // keep maximum 10 files on server
echo exif_imagetype($_FILES['Filedata']);
if ($_FILES['Filedata']['size'] <= $MAXIMUM_FILESIZE) {
move_uploaded_file($_FILES['Filedata']['tmp_name'], "./temporary/".$_FILES['Filedata']['name']);
$type = exif_imagetype("./temporary/".$_FILES['Filedata']['name']);
if ($type == 1 || $type == 2 || $type == 3) {
rename("./temporary/".$_FILES['Filedata']['name'], "./images/".$_FILES['Filedata']['name']);
} else {
unlink("./temporary/".$_FILES['Filedata']['name']);
}
}
$directory = opendir('./images/');
$files = array();
while ($file = readdir($directory)) {
array_push($files, array('./images/'.$file, filectime('./images/'.$file)));
}
usort($files, sorter);
if (count($files) > $MAXIMUM_FILE_COUNT) {
$files_to_delete = array_splice($files, 0, count($files) - $MAXIMUM_FILE_COUNT);
for ($i = 0; $i < count($files_to_delete); $i++) {
unlink($files_to_delete[$i][0]);
}
}
print_r($files);
closedir($directory);
function sorter($a, $b) {
if ($a[1] == $b[1]) {
return 0;
} else {
return ($a[1] < $b[1]) ? -1 : 1;
}
}
?>
This PHP code first defines two constant variables: $MAXIMUM_FILESIZE and $MAXIMUM_FILE_COUNT. These variables dictate the maximum size (in kilobytes) of an image being uploaded to the server (200KB), as well as how many recently uploaded files can be kept in the images folder (10). If the file size of the image currently being uploaded is less than or equal to the value of $MAXIMUM_FILESIZE, the image is moved to the temporary folder.
Next, the file type of the uploaded file is checked to ensure that the image is a JPEG, GIF, or PNG. If the image is a compatible image type, the image is copied from the temporary folder to the images folder. If the uploaded file wasn't one of the allowed image types, it is deleted from the file system.
Next, a directory listing of the image folder is created and looped over using a while loop. Each file in the images folder is added to an array and then sorted. If the current number of files in the images folder is greater than the value of $MAXIMUM_FILE_COUNT, files are deleted until there are only $MAXIMUM_FILE_COUNT images remaining. This prevents the images folder from growing to an unmanageable size, as there can be only 10 images in the folder at one time, and each image can only be 200KB or smaller (or roughly 2 MB of images at any time).
The SWF file uploads the image file to the remote PHP document, and displays it in the ScrollPane (which adds scroll bars if necessary). If you want to view a previously uploaded image, you can select the filename from the ComboBox instance on the Stage. If the user tries to upload an image that isn't an allowed image type (only a JPEG, GIF, or PNG image is allowed) or the file size is too big (over 200 KB), Flash displays the error message from the Message movie clip in the Library.
For a sample source file for this example, FileUpload.fla, see the Flash Samples page at www.adobe.com/go/learn_fl_samples. Download the Samples zip file and navigate to the ActionScript2.0/FileUpload folder to access this sample.
For more information on local file security, see About local file security and Flash Player.
For more information on writing PHP, go to www.php.net/.
Flash CS3
Send me an e-mail when comments are added to this page | Comment Report
Current page: http://livedocs.adobe.com/flash/9.0/main/00001054.html