Flash ActionScript 3.0 – Uploading an image

I’ve been having trouble implementing the code to upload an image to a server. The code is basically this:

Set the variables for the file reference, file types to filter by and the url to send the image to:

var imagesFilter:FileFilter = new FileFilter("Images", "*.jpg;*.gif;*.png");
var fileReference:FileReference = new FileReference();
var uploadURL:URLRequest;
uploadURL = new URLRequest ("upload.php");

Select which file you want to upload to the server.

fileReference.addEventListener(Event.SELECT, selectHandler);
fileReference.browse([imagesFilter]);

Function to tell Flash what to do once you have selected your file.

function selectHandler (event:Event):void {
var file:FileReference = FileReference(event.target);
file.upload(uploadURL);
}

Then use the following PHP code in a file called upload.php.

<?PHP
// The folder where the image will be uploaded to
$target_path = "uploads/";
/* Then add the original filename to the target path.
Result is "uploads/filename.extension" */
$target_path = $target_path . basename( $_FILES['Filedata']['name']);
if(move_uploaded_file($_FILES['Filedata']['tmp_name'], $target_path)) {
echo "The file ".  basename( $_FILES['Filedata']['name']).
" has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
?>

So, why wasn’t is working

So basically, this code wasn’t working, and I had no idea why. I kept getting the generic error [IOErrorEvent type="ioError" bubbles=false cancelable=false eventPhase=2 text="Error #2038"].

A nice relaxing sleep later I did some more searching and discovered this wonderful post: Romantika.name | Flash Uploader Error. Which basically informed me that there can be a security issue with Flash trying to upload things to a server. I updated my .htaccess file and ta da….all worked perfectly.

1 hello to “Flash ActionScript 3.0 – Uploading an image”

  1. 17Oct Polprav

    Hello from Russia!
    Can I quote a post in your blog with the link to you?

Leave a Reply