View comments | RSS feed

FileReference (flash.net.FileReference)


Object
    |
    +-flash.net.FileReference

public class FileReference
extends Object

The FileReference class provides a means to upload and download files between a user's computer and a server. An operating-system dialog box prompts the user to select a file to upload or a location for download. Each FileReference object refers to a single file on the user's hard disk and has properties that contain information about the file's size, type, name, creation date, modification date, and creator type (Macintosh only).

FileReference instances are created in two ways:

During an upload operation, all of the properties of a FileReference object are populated by calls to FileReference.browse() or FileReferenceList.browse(). During a download operation, the name property is populated when onSelect has been invoked; all other properties are populated when onComplete has been invoked.

The browse() method opens an operating-system dialog box which prompts the user to select any local file for upload. The FileReference.browse() method lets the user select a single file; the FileReferenceList.browse() method lets the user select multiple files. After a successful call to the browse() method, call the FileReference.upload() method to upload one file at a time. The FileReference.download() method prompts the user for a location to save the file and initiates downloading from a remote URL.

The FileReference and FileReferenceList classes do not let you set the default file location for the dialog box generated by browse() and download() calls. The default location shown in the dialog box is the most recently browsed folder, if that location can be determined, or the desktop. The classes do not allow you to read from or write to the transferred file. They do not allow the SWF file that initiated the upload or download to access the uploaded or downloaded file or the file's location on the user's disk.

The FileReference and FileReferenceList classes also do not provide methods for authentication. With servers that require authentication, you can download files with the Flash Player browser plug-in, but uploading (on all players) and downloading (on the stand-alone or external player) fails. Use FileReference event listeners to ascertain whether operations have successfully completed and to handle errors.

For uploading and downloading operations, a SWF file can access files only within its own domain, including any domains that are specified by a cross-domain policy file. If the SWF that is initiating the upload or download doesn't come from the same domain as the file server, you must put a policy file on the file server.

While calls to the FileReference.browse(), FileReferenceList.browse(), or FileReference.download()methods are executing, SWF file playback pauses on the following platforms: the Flash Player plug-in for Mac OS X, the external Flash Player for Macintosh, and the stand-alone player for Mac OS X 10.1 and earlier. The SWF file continues to run in all players for Windows and in the stand-alone player for Macintosh on Mac OS X 10.2 and later.

Availability: ActionScript 1.0; Flash Player 8

Example

The following example creates a FileReference object that prompts the user to select an image or text file to be uploaded. It also listens for any possible event.

import flash.net.FileReference;

var allTypes:Array = new Array();
var imageTypes:Object = new Object();
imageTypes.description = "Images (*.jpg, *.jpeg, *.gif, *.png)";
imageTypes.extension = "*.jpg; *.jpeg; *.gif; *.png";
allTypes.push(imageTypes);

var textTypes:Object = new Object();
textTypes.description = "Text Files (*.txt, *.rtf)";
textTypes.extension = "*.txt;*.rtf";
allTypes.push(textTypes);

var listener:Object = new Object(); 

listener.onSelect = function(file:FileReference):Void {
    trace("onSelect: " + file.name);
    if(!file.upload("http://www.yourdomain.com/yourUploadHandlerScript.cfm")) {
        trace("Upload dialog failed to open.");
    }
}

listener.onCancel = function(file:FileReference):Void {
    trace("onCancel");
}

listener.onOpen = function(file:FileReference):Void {
    trace("onOpen: " + file.name);
}

listener.onProgress = function(file:FileReference, bytesLoaded:Number, bytesTotal:Number):Void {
    trace("onProgress with bytesLoaded: " + bytesLoaded + " bytesTotal: " + bytesTotal);
}

listener.onComplete = function(file:FileReference):Void {
    trace("onComplete: " + file.name);
}

listener.onHTTPError = function(file:FileReference):Void {
    trace("onHTTPError: " + file.name);
}

listener.onIOError = function(file:FileReference):Void {
    trace("onIOError: " + file.name);
}

listener.onSecurityError = function(file:FileReference, errorString:String):Void {
    trace("onSecurityError: " + file.name + " errorString: " + errorString);
}

var fileRef:FileReference = new FileReference();
fileRef.addListener(listener);
fileRef.browse(allTypes);

See also

FileReferenceList (flash.net.FileReferenceList)

Property summary

Modifiers

Property

Description

 

creationDate:Date [read-only]

The creation date of the file on the local disk.

 

creator:String [read-only]

The Macintosh creator type of the file.

 

modificationDate:Date [read-only]

The date that the file on the local disk was last modified.

 

name:String [read-only]

The name of the file on the local disk.

 

size:Number [read-only]

The size of the file on the local disk, in bytes.

 

type:String [read-only]

The file type.

Properties inherited from class Object

constructor, __proto__, prototype, __resolve


Event summary

Event

Description

onCancel = function(fileRef:FileReference) {}

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

onComplete = function(fileRef:FileReference) {}

Invoked when the upload or download operation has successfully completed.

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

Invoked when an upload fails because of an HTTP error.

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.

onSecurityError = function(fileRef:FileReference, errorString:String) {}

Invoked when an upload or download fails because of a security error.

onSelect = function(fileRef:FileReference) {}

Invoked when the user selects a file to upload or download from the file-browsing dialog box.

Constructor summary

Signature

Description

FileReference()

Creates a new FileReference object.

Method summary

Modifiers

Signature

Description

 

addListener(listener:Object) : Void

Registers an object to receive notification when a FileReference event listener is invoked.

 

browse([typelist:Array]) : Boolean

Displays a file-browsing dialog box in which the user can select a local file to upload.

 

cancel() : Void

Cancels any ongoing upload or download operation on this FileReference object.

 

download(url:String, [defaultFileName:String]) : Boolean

Displays a dialog box in which the user can download a file from a remote server.

 

removeListener(listener:Object) : Boolean

Removes an object from the list of objects that receive event notification messages.

 

upload(url:String) : Boolean

Starts the upload of a file selected by a user to a remote server.

Methods inherited from class Object

addProperty, hasOwnProperty, isPropertyEnumerable, isPrototypeOf, registerClass, toString, unwatch, valueOf, watch



Version 8

Comments


rdoyle720 said on Oct 27, 2005 at 7:30 AM :
This example if I change absolutely nothing in the code, do a test movie and pick an image, will fire an onProgress and onComplete events, but doesn't actually do anything with the file I choose. If I add a loadMovie event to the onComplete to try to load the image, it tells me the image can not be found.
shimi2 said on Oct 27, 2005 at 3:15 PM :
Hi rdoyle720 - The example is demonstrative only and contains a URL "http://www.yourdomain.com/yourUploadHandlerScript.cfm" which you are supposed to replace with your own valid URL to the location of an upload script.
I'll make this clear in future docs. For a full working sample, including a URL that points to a valid PHP script, see http://livedocs.macromedia.com/flash/8/main/00001591.html.
Anders Thingholm said on Oct 31, 2005 at 2:31 PM :
How do I detect which folder (path) in which the file is located?

When I use the browse example I can select a local file - but since my movie doesn't know where the file is located I cannot load it into Flash.
tsamu said on Nov 7, 2005 at 4:22 PM :
in firefox
When swf calling FileReference.upload(handlerURL) method, the handler (which is
a server script) can't see session cookies

Steps to Reproduce:
1. page1> setcookie(cookiename,value)
2. page2 swf> FileReference.upload(handlerURL)
3. handlerURL (serverscript)> getcookie(cookiename) return null
No screen name said on Nov 25, 2005 at 4:38 AM :
Hi,

Is it possible to send other data with post at the same time the event occurs


Code:
var file_fr:FileReference = new FileReference();

upload_butn.onPress = function() {
file_fr.upload(myurl);
};

Thanks
No screen name said on Nov 29, 2005 at 10:29 PM :
Is there a ASP/ASP.NET example of this functionality?
No screen name said on Nov 30, 2005 at 10:28 AM :
It's possible to change the "select file to upload" string? on the window title bar?
No screen name said on Nov 30, 2005 at 4:08 PM :
Can i send any other Variables with the FileReference.upload method?
Or i have to start a LoadVars.send somewhere?
---
I want to send a custom filename what is supposed to be the uploaded file's name (instead of the file's original name). Please.
pitcher_32 said on Dec 1, 2005 at 2:49 PM :
using FileReference in a form application doesn't seem to work.
myReference.browse(); shows nothing. using the same code in a single form file works as expected. Is there a known problem using FileReference in form applications ??
No screen name said on Dec 8, 2005 at 12:36 PM :
"Can i send any other Variables with the FileReference.upload method?
Or i have to start a LoadVars.send somewhere?"

That's my suggestion:

filename="yourname";
docFile.upload("script.php?name="+filename+"&anothervar="+anothervar);

It sends file with variables using method "GET"
No screen name said on Dec 15, 2005 at 5:57 AM :
hi

i'm developing on my localhost (WINDOWS XP). I spent 4 hours debugging (filereference.upload() executed php script on localhost 2 TIMES ) until i checked log files of my server:
mod_gzip: DECLINED:POST_TOO_BIG

i found in google: this is a problem specific to the windows platform. :-)

i hope the info will help somebody (and i hope it will work on linux server)

martin
No screen name said on Dec 26, 2005 at 7:37 PM :
Does anyone know how to use fileDownload with the Servlet?
play(); said on Jan 15, 2006 at 9:54 AM :
I have the FileReference class working fine - however it fires my PHP script twice.

Has anyone else had this? It's a real problem.

Regards, Sam
No screen name said on Jan 15, 2006 at 8:04 PM :
how can I get the local file's path~
thanks a lot
shimi2 said on Jan 16, 2006 at 3:05 PM :
Per the documentation: The FileReference API does not allow you to read from or write to the transferred file and does not allow the SWF file that initiated the upload or download to access the uploaded or downloaded file or the file's location on the user's disk.
No screen name said on Jan 20, 2006 at 7:48 AM :
There is a catch if you want to send variables.

Although it says it has to be a form with the POST method, to send variables you have to use the GET method with the upload url (this is done by passing variables to the url with '?variableone=1&vartwo=2'...)

If anyone gets to send variables with the POST method, please mail me
Valetta Road said on Feb 10, 2006 at 4:13 AM :
When I create a new movie and put everything in the first frame I can get the file upload to work perfectly. If I then try to run the same movie in a loader component within another movie the upload fails. I've tracked the problem down, which is that fileReference.Upload is sending nothing, as if the file is lost within Flash and therefore can't be posted to the backend script. Is this true? Does anyone have a working example using fileReference within a loader component?
devoid said on Feb 28, 2006 at 3:49 PM :
in reply to No screen name [said on Jan 20, 2006 at 7:48 AM]

> If anyone gets to send variables with the POST method, please mail me

After many hours trying to get extra variables through to the server, I've found a workaround in Perl, by examining $ENV{'QUERY_STRING'}.

The POST method allows the file to be uploaded and you can get any ?var1=foo&var2=bar variables from $ENV{'QUERY_STRING'}. Some useful looking (ie; i've not tried them!) PHP scripts which made me think of this can be found here :
http://www.pixelficker.com/flash-8-file-upload-rc-1/
No screen name said on Mar 14, 2006 at 6:32 PM :
Even after creating a cross-domain policy I get a "securitySandboxError" when uploading.

My policy file at http://domain.com/pol.xml
<cross-domain-policy>
<allow-access-from domain="*" to-ports="*"/>
</cross-domain-policy>

I'm trying to up load from a different domain to http://domain.com/put.php

Any ideas?
Jooky One said on Mar 17, 2006 at 8:51 AM :
In the documentation it states that only files up to 100mb are supported, but I have successfully uploaded files in excess of 300mb. You just have to adjust the maximum file size on your server side installation which usually has a default limitation well below those numbers(ASP.NET =8mb, PHP=2mb). I have a PHP backended web form for uploading files in a portal with my PHP installation set to accept files up to 400mb and Flash has performed beautifully.
No screen name said on Mar 27, 2006 at 5:57 PM :
I can't get it to send vars with GET?

AS:
selectedFile.upload("upload.php?path="+path);

PHP:
move_uploaded_file($_FILES['Filedata']['tmp_name'], "./
files/".$_GET['path']."/".$_FILES['Filedata']['name']);

Has anyone sent extra vars using PHP?
No screen name said on Mar 28, 2006 at 12:53 PM :
This is great! But since I'm writing code how Macromedia says I should(object oriented), how would you do this in a class file? listener.method isn't allowed.
M@dster said on Apr 11, 2006 at 1:20 AM :
Is there any way to send any data back from the server?

I mean, it just fires the onComplete event upon succesfull upload, but what if I would like to send new id of the picture or similar back to Flash from the server?
devoid said on Apr 11, 2006 at 9:20 AM :
in reply to M@dster,

I've not achieved this either, my work around is to use the file
upload call to save the file onto the server with a standard
temporary name (eg. temp.jpg),

then, when upload is complete, I call another server script from flash
(using LoadVars.sendAndLoad), sending a variable with what to
change the name of that file to (eg. userpic23.jpg)
emansouri said on Jun 21, 2006 at 7:54 AM :
The only way I was able to figure out how to send data to the server along with the file uploads was appending the values to the URL as:

script.pl?userId=1&method=uploadFile

in the serverside script, the variables do not seem to be made available the way you would expect them in a GET or POST request. I had to use the QUERY_STRING environment variable, in Perl:

my $queryString = $ENV{'QUERY_STRING'};

I can deal with this for now because I am so happy to finally have a way to upload files independent of HTML and Javascript code but it seems a simple method to add variables that get sent to the server with the file is a necessary thing.
Phomari7 said on Aug 5, 2006 at 6:58 PM :
When is onComplete called? As soon as the php script is invoked, or after the script has completed?
eboyjr13 said on Aug 29, 2006 at 7:15 PM :
hi
Anyone know how to get the local file's path?
Thanx
dgbdesign said on Sep 8, 2006 at 6:41 AM :
I've successfully used the FileReferenceList to upload multiple files,
however, when the files are selected locally, they are uploaded in a
seemingly arbitrary (but consistent) order, rather than alpha-numerically
by file name. Performing sortOn on the fieldName "name" on the
FileReferenceList array works (Array.DESCENDING reverses the
original file order), but the new sort is still not alpha-numeric by file
name, as if the actual file name has extra information in it.

The files I'm attempting to sort all are named like:
lg400.jpg
lg401.jpg
lg402.jpg

but the array order (and hence upload order) might be something like:
lg401.jpg
lg400.jpg
lg402.jpg
damon.default said on Sep 26, 2006 at 5:30 AM :
Trying to use this, I've found that:
- cookies don't work properly from firefox
- flash for firefox can't upload over ssl
- there is no flash player 8 for linux

So as far as upload goes, the amazing cross platform flash plugin works in IE on windows, and partially works in safari for mac. This is such a missed opportunity to do multi file select properly across platforms.
gazpachu2002 said on Oct 9, 2006 at 6:58 PM :
FileReference.browse causes a critical crash of Flash Player 8 or 9. Tested on Flash 8 IDE, Internet Explorer 6 and Firefox under Windows Media Center 2005.

The application works fine in any other environment... Any clue of how to fix this?
Ritesh Batra said on Oct 11, 2006 at 3:39 AM :
need help on the sandBox error.

I have put the crossdomain file on the server but still problem is there.
I have using aspx page to save the file.
Lindeskov said on Nov 27, 2006 at 4:05 AM :
I use this code with its download capasity.
But with some computers the download stops showing the onSelect and do not go on (it works perfectly on other computers!) - does anyone know what that could be?

Thank you
Frank
No screen name said on Jan 19, 2007 at 12:46 PM :
hi
i wanna use FileReference just to locate le file, i need just the url of my file in my hdd.

help me
ralphdelnoy said on Jan 26, 2007 at 9:39 AM :
Does anyone know if its possible to get the bytesloaded of the serverside script instead of the the uploaded file?
No screen name said on Feb 8, 2007 at 2:00 PM :
I use this in asp.net

if (fileName.Length > 0)
{
Request.Files[0].SaveAs(Server.MapPath("Photos/" + fileName));
}

Response.Clear();
Response.Write("");
Response.End();


but I cannot get this to work with Safari on Mac. The flash dev told me to add the Response.Write("") return but doesn't seem to make a difference. The flash just hangs during upload on the mac but the file is uploaded to the server.
Cyandi_Man said on Feb 18, 2007 at 4:45 PM :
I am just trying to make my fileReference download function work properly...i am using the folowing code:

on(release){

import flash.net.FileReference;

var listener:Object = new Object();

listener.onSelect = function(file:FileReference):Void {
trace("onSelect: " + file.name);
}

listener.onCancel = function(file:FileReference):Void {
trace("onCancel");
}

listener.onOpen = function(file:FileReference):Void {
trace("onOpen: " + file.name);
}

listener.onProgress = function(file:FileReference, bytesLoaded:Number, bytesTotal:Number):Void {
trace("onProgress with bytesLoaded: " + bytesLoaded + " bytesTotal: " + bytesTotal);
}

listener.onComplete = function(file:FileReference):Void {
trace("onComplete: " + file.name);
}

listener.onIOError = function(file:FileReference):Void {
trace("onIOError: " + file.name);
}

var fileRef:FileReference = new FileReference();
fileRef.addListener(listener);
var url:String = "http://www.djlba.com/logos/Sweatlogo300dpi.jpg";
if(!fileRef.download(url, "Sweatlogo300dpi.jpg")) {
trace("dialog box failed to open.");
}
}

however i need to know how to make the downloading status bar to show so the user knows somthing is in fact downloading and in
firefox it does not do anything at all.

please help!
No screen name said on Mar 16, 2007 at 9:05 PM :
Is there anyway to change the name "Filedata"? i am trying to make a frontend to an upload script where the filename is "FILE1" and i need to know if there is a way to somehow change the name. Any method would be helpful
jothiraj said on Apr 12, 2007 at 2:41 AM :
Hi,
Is there any way to get the local file's path(from hdd) using FileReference object of flash.

Thank you.
Rocketkid said on Apr 23, 2007 at 9:00 PM :
jothiraj ...

I haven't found a way to do that.
BUT you can use Javascript.

Use the
import flash.external.*; class -- please search for that, there are lotsof tutorials

and call a javascript function

In the javascript make a new active x object
new ActiveXObject("Scripting.FileSystemObject")

and use the property below to get the pathname.
GetParentFolderName(window.location.pathname)

You can return this back to flash.

It ay take a bit of researching those functions and it's the only way I have found to do it.
I hope there is an easier way out there.
zivo13 said on May 4, 2007 at 2:00 PM :
regarding to filereference is working fine with files no bigger than 100ks, whe i try to upload bigger files it just freeze, it stop on 22% or 64%, etc any ideas?
thanks and best regards
risky57 said on May 9, 2007 at 7:10 AM :
how can i get the absolute path/location of the chosen file?
is this possible?
i just want the user to select a file and send the absolute location of that to a jsp.

any help would be appreciated
No screen name said on May 22, 2007 at 12:09 PM :
Why FileReference doesn't allow local paths like getURL or loadMovie or loadVars or loadClip etc. does.

Example (security model: acess local files):
//suppose this swf is on server

var file:FileReference = new FileReference();
var path:String = "Data folder/some file.ext"

getURL(path) <-- GOOD
file.download(path) <-- NOT GOOD

Is there any bypass ??
nehg said on Jul 11, 2007 at 6:21 AM :
Tried hard to get this working with JSP; could not find single sample. If anyone has idea please share.
Tanmoy Das said on Jul 26, 2007 at 12:49 AM :
How do I determine the path of a file selet by FileReference.browse(); method pls mail me if any body knows my mail id is info_tanmoy@yahoo.co.in I will be very much greatful to that person
chepri said on Aug 1, 2007 at 6:57 AM :
How do I detect which folder (path) in which the file is located?

When I use the browse example I can select a local file - but since my movie doesn't know where the file is located I cannot load it into Flash.
No screen name said on Aug 29, 2008 at 12:48 PM :
There seems to be a bug here with the Mac version of the FileReference interface. I have an upload script that work just fine on Windows under Safari, IE 6 and 7, as well as Firefox 2 and 3. Mind you this is with Vista, Server 2003, and XP.

However, the exact same script (running on the same web server), fails on all browsers on the Mac.

Here's the trick though: the file being uploaded is indeed transferred to my destination folder on both platforms. However, the onProgress event fails to fire on the mac, which effectively breaks my script such that a latter ExternalInterface.call method also fails, and thus my app breaks.

So, it seems as if the onSelect call works, as does onOpen, but nothing after that.

Bug?
rene.jaspers said on Mar 12, 2009 at 8:23 AM :
Hey,

i was searching for a way to send additional data through the POST when uploading a file, as are many others, seached a lot, found nothing.

Then I tried some different techniques, and voila:

when u use this code, you can send any kind of data with in the POST

private var fileUpLoader:FileReference;
private var myUrlRequest:URLRequest;

private function startUpload():void {
var uploadToUrl:String = "http://yourdomain.com/upload/upload_handler.php";

myUrlRequest = new URLRequest();
myUrlRequest.url = uploadToUrl;
myUrlRequest.data = new URLVariables();
myUrlRequest.data.user_id = 1;

fileUpLoader = new FileReference();
fileUpLoader.addEventListener(Event.SELECT, selectHandler);
fileUpLoader.browse();
}

private function selectHandler (evt:Event):void {
fileUpLoader.upload(myUrlRequest);
}

// PHP File

$fileData = $_FILES["Filedata"];
$fileName = $fileData["name"];
$tmp_name = $fileData["tmp_name"];

file_put_contents('debug1.txt, move_uploaded_file($tmp_name, $fileName));
file_put_contents('debug2.txt', $_POST['user_id']);

// now you have 3 new files
1. the file you uploaded
2. debug1.txt containing true (if all went well);
2. debut2.txt containing 1, the user_id you specified in the AS

I hope i can help someone with this.. took me long enough :\

(it can contain errors, becouse i typed it here, it's not a copy of my script)

 

RSS feed | Send me an e-mail when comments are added to this page | Comment Report

Current page: http://livedocs.adobe.com/flash/8/main/00002204.html