« Using the onHTTPStatus handler | Main | Using SWF Metadata in Flash 8 »

Creating a File upload application using FileReference API

Listen to this article Listen to this article :: Talkr

Feature - FileReference API
Level - Intermediate
Audience - Developers

FileReference API provides methods using which one can download or upload files from/to a server. Each FileReference object maps to a single file which can be uploaded or downloaded from/to a server. You can get the following properties of a file using the FileReference API:

  • File Size
  • File Type
  • File Name
  • Creation Date
  • Modification Date
  • Creator type (Mac only)

Due to security reasons you CANNOT get the file path of the file which you are uploading to the server.

The following methods are available in the FileReference API:

and the events are:

onCancel = function(fileRef:FileReference) {}

Invoked when the user dismisses the file-browsing dialog box.

Ex: 

listener.onCancel = function(file:FileReference):Void {

    log.addItem(“File upload/download cancelled by user”);

}

onComplete = function(fileRef:FileReference) {}

Invoked when the upload or download operation has successfully completed.

Ex:

listener.onComplete = function(file:FileReference):Void {

    log.addItem(“File upload/download successful”);

    // Write code here to do manipulations or display the uploaded file

}

onHTTPError = function(fileRef:FileReference, httpError:Number) {}

Invoked when an upload fails because of an HTTP error.

Note: This event applies only to File Upload and not File Download. If a file download fails, an IO Error is reported instead of a HTTP Error.

Ex:

listener.onHTTPError = function(file:FileReference, httpError:Number):Void {

    log.addItem(“HTTP Error :” + httpError);

    // Write code here to do corrective actions

}

onIOError = function(fileRef:FileReference) {}
Invoked when an input/output error occurs.

onOpen = function(fileRef:FileReference) {}
Invoked when an upload or download operation starts.

onProgress = function(fileRef:FileReference, bytesLoaded:Number, bytesTotal:Number) {}Invoked periodically during the file upload or download operation.

Ex:

listener.onProgress = function(file:FileReference, bytesLoaded:Number, bytesTotal:Number):Void {

log.addItem("bytesLoaded: " + bytesLoaded + " bytesTotal: " + bytesTotal);

}

onSecurityError = function(fileRef:FileReference, errorString:String) {}
Invoked when an upload or download fails because of a security error.

Note: In most of the cases this error occurs due to the sandbox restriction. Check if the crossdomain.xml file is present and configured properly in the site to which you are uploading the file.

Ex:

listener.onSecurityError = function(file:FileReference, errorString:String):Void {

   log.addItem("Security Error: " + file.name + " errorString: " + errorString);

}

onSelect = function(fileRef:FileReference) {}
Invoked when the user selects a file to upload or download from the file-browsing dialog box.

Ok, enough of lecture. Let’s get into implementing a example using FileReference API which will be a application through which you can upload files into a web server.

So what do you need to implement this example?

  • The Flash application
  • A PHP/ASP/JSP page which will catch the file stream and create the file on the server
  • A folder on the Web server with write permission.

Flash application:

This file contains all the methods that are present in the FileReference and the usage example.

PHP code:

<?PHP
$target_path = "uploads/";
$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!";
}
?>

For a detailed explanation of this code, see here.

Download the example files here.

Just unzip the archive into a folder and upload it to your web server and you are ready to upload files into the server.

Additional References :

Flash 8 File-Upload (RC-1)
Uploading files with Flash 8
Flash: Force Download… No more dirty tricks in Flash 8

TrackBack

TrackBack URL for this entry:
http://www.lastashero.com/tutorials/mt-tb.cgi/3

Listed below are links to weblogs that reference Creating a File upload application using FileReference API:

» Tutorial : Creating a File upload application using FileReference API from Last ActionScript Hero - Blog - Flash & Related Technologies
I have posted a new tutorial on "Creating a File upload application using FileReference API" in the tutorial section of the site. Check it out here.... [Read More]

Questions & Comments

hi,
your tutorial is excellent !

Thanks Jean !!

- kp

For God´s sake! What about Macromedia ColdFusion as a server side script? You must put it on!

For God's sake, here is the code ;)

<cffile action="upload" fileField="Filedata" destination="c:\web\uploads\" nameConflict="makeUnique"/>;

For a detailed reference, look here : http://livedocs.macromedia.com/coldfusion/6.1/htmldocs/tags-p35.htm

Cheers,
KP

Nice Work man..!

I love this & this is the only sample which is working in my localhost compare with all other flash 8 uploading sample in the net.
Guess this is a better site to check frequently.

Thanks,
Anja

Any Change of an ASP Example? I've got PHP working fine, but that "Zero" test upload it does is killing my ASP... Any thoughts?

I keep getting a HTTP Error: 500 when I try the downloaded source files -- any idea why that might be?

Otherwise a great tute!

Echo : I have not tried it out with ASP and I am not good at it too. There is a tutorail on file upload here : http://www.tutorialized.com/tutorial/Understanding-File-Upload/1945 you can check this out.

Hope this helps !

Cheers,
KP

dmack : HTTP Error: 500 when you try to download the source file !?? strange I have not got any complaints of that sort till now. Anyway you can try the direct URL : http://www.lastashero.com/tutorials/images/FileReference.zip. If even this does not work just shoot a mail to kp AT lastashero DOT com with your mail id and I will send it to you directly.

Cheers,
KP

Great tutorial! Just wondering though; the only object I could get the actionscript to react to was a button component. I tried attaching my own button symbol, but the browse window never popped up. Any idea if it must be a button component?

is it possible to post a working asp script example?

i can't figure it out :(

Hi, I´m from Argentina and found this great tutorial but I can´t upload a file yet, and I am desperate trying to develop this little mask for my first client to upload his photos directly to the web server. I downloaded the file, unzip it, opened the fla file, changed the URL addres to point where I saved the PHP file. I open my browser on www.blupix.com.ar/filereference.html and seems to work 100% and says it uploaded it but I cant find any files in my uploads folder on the server. Is it a matter of permissions, I talk to my host man and he says he supports PHP . What ELSE CAN I DO, I NEED TO WIN MY FIRST CLIENT PLEASE ! HELP
THKS FOR ALL

In the PHP file, there are two "echo" commands. So I wondering how I can get those strings into flash?
I know how to send variables with "upload" command from flash to php but I don't have anymore ideas to get information from php file into flash.
If someone can, could you please help me?

Very helpful. I found the code for C# ASP.NET that worked right away with this tutorial. Sorry, don't remember who to credit.

private void Page_Load(object sender, System.EventArgs e)
{
HttpFileCollection uploadedFiles = Request.Files;
string Path = Server.MapPath(saveToFolder);
for(int i = 0 ; i {
HttpPostedFile F = uploadedFiles[i];
if(uploadedFiles[i] != null && F.ContentLength > 0)
{
string newName = F.FileName.Substring(F.FileName.LastIndexOf("\\") + 1);
F.SaveAs(Path + "/" + newName);
}
}
}

is it possible to upload Word Docs????

Hey, Excellent tut. One question though. How can i implement a cancel option for the upload? What i need to do is once the upload starts, the Upload button turns into a Cancel button. Using the fileRef.cancel(); works but triggers also the IOError message, which i cannot override.

Thx

You got some great code here! Thanks a ton!

great tutorial! im wondering why the mimetype of the uploads is always 'application/octet-stream' no matter what type of file it is.

do you know of anyway of cheking the actual filetype, because flash does it by extention only. so you can change the extention of any file to an excepted type in your 'imageTypes' array and it will upload.

Hello,
This cfc script just won't work for me. I'm no coldfusion expert, so I might be doing something wrong.. Please help if u can..
The Flash stuff is just as in your tut..
Here is the cfc code.



nameconflict="makeunique"/>

I do not get an onComplete error or any other error, but when I check no file has been uploaded! :( Do I need to reference the file "name" somehow in the cfc?
Thanks!

Nice example, works great, and very easy to follow, i do have a question... is there any way to do this with only flash? as in no php, asp, or jsp... is there any way to upload the file using only flash?

hello, thanks a lot for ur information.

Thanx. Good

Hi, like fozzo from Argentina I have done everything in the tutorial and the flash file says it has uploaded but there is no file on my server. I am running Win2003 server,IIS6 and PHP5. Hope you can suggest what I am doing wrong. I get no errors

Post a comment

(If you haven't left a comment here before, you may need to be approved by the site owner before your comment will appear. Until then, it won't appear on the entry. Thanks for waiting.)