In an earlier example we looked at “Downloading files in Flex using the FileReference class“, but It looks like we haven’t ever looked at file uploads.
The following example shows how you can use the FileReference class’s browse() method to allow users to select and upload a single file to a Web server.
If you want to allow users to upload multiple files at once, you would use the FileReferenceList class instead of FileReference.
Full code after the jump.
<?xml version="1.0" encoding="utf-8"?>
<!-- http://blog.flexexamples.com/2007/09/21/uploading-files-in-flex-using-the-filereference-class/ -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
layout="vertical"
verticalAlign="middle"
backgroundColor="white"
creationComplete="init();">
<mx:Script>
<![CDATA[
private var fileRef:FileReference;
private const FILE_UPLOAD_URL:String = "http://www.YOUR-WEBSITE-HERE.com/fileref/uploader.cfm";
private function init():void {
fileRef = new FileReference();
fileRef.addEventListener(Event.SELECT, fileRef_select);
fileRef.addEventListener(ProgressEvent.PROGRESS, fileRef_progress);
fileRef.addEventListener(Event.COMPLETE, fileRef_complete);
}
private function browseAndUpload():void {
fileRef.browse();
message.text = "";
}
private function fileRef_select(evt:Event):void {
try {
message.text = "size (bytes): " + numberFormatter.format(fileRef.size);
fileRef.upload(new URLRequest(FILE_UPLOAD_URL));
} catch (err:Error) {
message.text = "ERROR: zero-byte file";
}
}
private function fileRef_progress(evt:ProgressEvent):void {
progressBar.visible = true;
}
private function fileRef_complete(evt:Event):void {
message.text += " (complete)";
progressBar.visible = false;
}
]]>
</mx:Script>
<mx:NumberFormatter id="numberFormatter" />
<mx:Button label="Upload file"
click="browseAndUpload();" />
<mx:Label id="message" />
<mx:ProgressBar id="progressBar"
indeterminate="true"
visible="false" />
</mx:Application>
You’ll notice the previous example doesn’t have a SWF or file upload URL. That would be because I don’t want all of you uploading files to my server. :)
In the previous example, I wrapped the call to fileRef.size in a try..catch block. In ActionScript 3.0, Flash Player throws an error if you attempt to get the size of a zero-byte file.




Hi, looks like a good example but I am confused about one thing
in particular. What serverside script are you using to upload the file?
I noticed this URL “http://www.YOUR-WEBSITE-HERE.com/fileref/uploader.cfm”;
which I’m guessing is the file to handle the upload? Can you clarify whether
a serverside script e.g PHP is needed and if so, would you mind posting
an example. Much appreciated. Love the site by the way, its very useful.
using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Drawing; using System.Web; using System.Web.SessionState; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; using System.Text; namespace UploadTest { /// /// Summary description for WebForm1. /// public class WebForm1 : System.Web.UI.Page { private void Page_Load(object sender, System.EventArgs e) { string sResult = "OK"; if(Request.Files.Count > 0) { HttpPostedFile httpPostedFile = Request.Files[0]; try { string sFilePath = Server.MapPath(httpPostedFile.FileName); httpPostedFile.SaveAs(sFilePath); } catch(Exception ex) { sResult = ex.Message; } } else sResult = "No file was uploaded."; Response.ContentType = "text/xml"; Response.ContentEncoding = Encoding.UTF8; Response.Write("<testupload><result>" sResult "</result></testupload>"); } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent() { this.Load = new System.EventHandler(this.Page_Load); } #endregion } }Woops - sorry I posted before the message was completed.
The previous code is for .NET
The line
Response.Write("" sResult "");should read
Response.Write("<testupload><result>" sResult "</result></testupload>");[Edit: Peter: Thanks Steve! I edited your comment above.]
Adam,
Yes, you will need a server-side script that will accept a file and write it to the hard drive (or whatever you want to do with the file). Here’s my test script that I wrote in ColdFusion:
<cfsilent><cfsetting enablecfoutputonly="true" /> <cfset req = getHTTPRequestData( )> <cffile action="UPLOAD" filefield="Filedata" destination="#ExpandPath('.')#" nameconflict="MAKEUNIQUE"> <cfsavecontent variable="info"> <html> <head></head> <body> <cfdump label="CFFILE" var="#cffile#"> <cfdump label="getHTTPRequestData()" var="#req#"> <cfif IsDefined("FORM")> <cfdump label="FORM" var="#FORM#"> </cfif> <cfif IsDefined("URL")> <cfdump label="URL" var="#URL#"> </cfif> </body> </html> </cfsavecontent> <cffile action="WRITE" file="#ExpandPath('./')##cffile.serverFileName#.dump.html" output="#info#" addnewline="Yes"> </cfsilent><cfsetting enablecfoutputonly="false" /> <cfcontent reset="true" /> <cfoutput>fileName=#CFFILE.serverFile#&fileSize=#CFFILE.fileSize#</cfoutput>It’s probably quite overkill as it has a bit of debug code in there (it uploads the file and dumps all the file properties to an HTML file so I can see what’s happening).
If you are using ColdFusion, I believe you can just use the following one line which uploads a file with the header name “Filedata”, and saves it to the same directory as the ColdFusion template:
<cffile action="upload" filefield="Filedata" destination="#ExpandPath('./')#" nameconflict="OVERWRITE" />Although the code is really simple and elegant, note that you’d always want to be careful when accepting file uploads. You would want to try and verify that users aren’t uploading executable server-side scripts which they could then call on the server via HTTP. For example, a user could try and upload a PHP script which tries to delete files or databases from your website.
I’m not a PHP programmer, so I’ll have to leave that for another commenter (or I’m sure there are several solutions on the web if you Google for it). In fact, the Flash documentation does have some sample PHP upload script posted here: “Working with file upload and download“.
I also found the following article on the Adobe ColdFusion Developer Center, “Multiple file upload with Flex and ColdFusion“.
Happy Flexing!
Peter
Setve,
Thanks for the .NET solution! That’s outstanding!
Anybody have a snippet for PHP?
Peter
Hi ….
will be great if anyone post php code for uploading !
Saeed Ashour,
You can try the PHP code in the Adobe documentation at: http://livedocs.adobe.com/flash/9.0/main/00000320.html
You may need to tweak the code a bit, as it looks like the code limits the size of upload that will be accepted (max file upload size appears to be 200KB) and it is also checking the file’s type and only allowing certain file types (such as JPEG, GIF and PNG).
In fact, here’s the code description from the documentation:
You can also check out this entry in the Adobe Flex Cookbook, “Uploading files from Flex using PHP“.
Hope that helps,
Peter
Saeed Ashour
said: “great if anyone post php code for uploading !”
Me three! I have been googling for ages looking for a Flex multi-upload
example using PHP but most seem to be using ColdFusion which I know
nothing about unfortunatly, kind of a big ask but would someone mind sending
me an example? My email is - dyso_au (AT) hotmail.com
or a link would do :)
Anyone with a Flex muti-upload example using PHP?
My email is - dyso_au (at) hotmail.com or a link will do :)
Adam,
You can try this link for a multi file upload using php
http://weblog.cahlan.com/2006/12/flex-upload-component.html
Cheers!
Hi. This example is great. One question though. Your server generates a response giving the status of the upload from it’s point of view. How is this response accessed from Flex?
Thanks
Mark
I have been trawling for a while looking for how you get the server’s response back. So far the best I have seen is setting an HTTPStatus event handler, like this:
The handler looks like this:
private function onHTTPStatus (event : HTTPStatusEvent) : void { Alert.show ("Error:" event.status); }If the server returns a HTTP status other that 200, this handler is called. In my PHP server, I do something like this:
if ($fileexists) header("HTTP/1.0 501 file exists"); else if ($couldnotsave) header("HTTP/1.0 502 could not save"); else header("HTTP/1.0 200 all ok");In actionscript, event.status will only get the status number. i.e. it will get “501″ and not “501 file exists”.
Note that after the HTTPStatus event, a IOErrorEvent is also issued.
Mark
I’m back! The way to get the response is easy (but not documented in the Flex doc from what I can see):
fileRef.addEventListener(DataEvent.UPLOAD_COMPLETE_DATA, onUploadCompleteData); private function onUploadCompleteData (event : DataEvent) : void { Alert.show (event.data); }Data contains whatever was issued, so in my PHP:
echo “hello”;
puts “hello” in event.data.
Hope this saves someone some time.
Mark
Mark,
Good work, you beat me to a response! Correct, the way to grab the server response is by listening for the
uploadCompleteDataevent like you said. It should be documented in the Flex 2.0.1 language reference documentation (click here).I’ll undoubtedly cover this in an upcoming example as this is relatively new to Flash Player (added in Flash Player 9.0.28.0, I believe).
Peter
Hi there, I’ve been looking for a working example for server side written in JSP for upload and download file. Will appreciate anyone who can give me the code.
For those of you who want to use Steve’s ASP.NET fileupload in VS 2003 modify these minor errors:
1. Change this:
Response.Write(”" sResult “”);
to this:
Response.Write(”" sResult “”);
2. Change this:
this.Load = new System.EventHandler(this.Page_Load);
to this:
this.Load = new System.EventHandler(this.Page_Load);
For some reason I couldn’t get this to work in VS 2005. Great job Steve for the .net code.
Peter, are ” ” (plus signs) disabled?
Anthony,
Ha, seemingly. Posting comments have always been kind of buggy in this template (its very AJAX heavy).
Try escaping the + signs with a backslash.
Similarly, excape > signs with > and < with <
Sigh,
Peter
(blah, i see hwo hard it is to post the “+” signs. try wrapping everything in a <pre /> tag and cross your fingers.)
any example of for file upload using JSP and then will display also hash code in Flex??? Thanks.
for jsp:
items = upload.parseRequest(request);
int counter = 0;
for(FileItem item : items) {
try {
File uploadedFile = new File(uploadDir File.separator item.getName());
item.write(uploadedFile);
out.println(”" uploadedFile.getAbsolutePath() “”);
}
catch(IOException ioe) {
System.out.println(”Problem copying temp file. ” ioe);
}
try {
MessageDigest md = MessageDigest.getInstance(”MD5″);
byte[] message = item.getString().getBytes();
md.update(message);
byte[] messageDigest = md.digest();
StringBuffer sb = new StringBuffer();
for(int i=0; i” sb.toString() “”);
}
catch(Exception e) {
System.out.println(”Unknown hash algorithm ” e);
}
counter ;
}
%>
——————–
this works with Apache Tomcat 5.5
an example here: http://www.webtitude.com/uploadToolTest2/Uploader.html
don’t bother about uploading so much. the script there deletes the file from server after hash code is displayed.
- vonnhugo (a.k.a. kris) with rey’s help for the JSP :)
yikes… i forgot that codes will not show well here. but the idea is there. email me (vonnhugo[at]hotmail.com) if you need these craps. :D
Update: Here’s the code:
<%@page import="java.io.IOException"%> <%@page import="java.io.File"%> <%@page import="java.io.InputStream"%> <%@page import="java.io.FileInputStream"%> <%@page import="java.security.MessageDigest"%> <%@page import="org.apache.commons.fileupload.FileItem"%> <%@page import="java.util.List"%> <%@page import="org.apache.commons.fileupload.servlet.ServletFileUpload"%> <%@page import="org.apache.commons.fileupload.disk.DiskFileItemFactory"%> <%@page import="org.apache.commons.fileupload.FileUpload"%> <?xml version="1.0"?> <myUpload> <% String uploadDir = pageContext.getServletContext().getRealPath("uploads"); File dir = new File(uploadDir); if(!dir.exists()) { dir.mkdir(); } DiskFileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); @SuppressWarnings("unchecked") List<FileItem> items = upload.parseRequest(request); int counter = 0; for(FileItem item : items) { File uploadedFile = new File(uploadDir + File.separator + item.getName()); try { item.write(uploadedFile); out.println("<file"+ counter +">"+ uploadedFile.getAbsolutePath() +"</file"+ counter +">"); } catch(IOException ioe) { System.out.println("Problem copying temp file. " + ioe); } InputStream is = null; try { MessageDigest md = MessageDigest.getInstance("MD5"); //byte[] message = item.getString().getBytes(); //md.update(message); byte[] buffer = new byte[1024]; is = new FileInputStream(uploadedFile); int read = 0; while( (read = is.read(buffer)) > 0) { md.update(buffer, 0, read); } byte[] messageDigest = md.digest(); StringBuffer sb = new StringBuffer(); for(int i=0; i<messageDigest.length; i++) { sb.append(Integer.toHexString( (int)(messageDigest[i] & 0xff) )); } out.println("<md5hash"+ counter +">"+ sb.toString() +"</md5hash"+ counter +">"); } catch(Exception e) { System.out.println("Unknown hash algorithm " + e); } finally { if(is != null) { is.close(); } } counter++; } %> </myUpload>Anyone have problems using multiple uploads with a Windows box? I have a great upload that works great on any mac computer but IO_ERROR on any windows box…
BTW, I am using the Adobe example scripts and trapping for IO_Error, i think it resutls in #2038..
any insight would be great , thanks
i think it’s a problem of rights to file or directory from/to where we want to Download/Upload
could u tell me how to upload files on server from flex to Ruby on Rails ?
Hello abhishek
even i am looking for the same thing.
i am using RoR as back-end in my flex project.
Please anyone guide me regarding ruby code for uploading the files.
thanks in advance.
What happens if you want to upload (import might be a better term) a file into a client side component such as an RichTextEditor box? The user would then be able to edit the file, and either save it or send it to the server.
Anyone know how to do this preferably without a server roundtrip.
hi! i just want to know how to upload a file on server using flex2.
please send reply to this mail as soon as poosible….
asha,
Check out the FileReference class (http://livedocs.adobe.com/flex/201/langref/flash/net/FileReference.html), or more specifically, the FileReference class’s upload() method.
Peter
i am using backend as java,can anyone post the server side code for image uploading in java which uses this code in the client side
is there any way to get the absolutepath in flex?
rconceiver,
No.
Peter
Hello! i’m trying to upload files to .net with c#, but i’m a newbie with .net, in what kind of file do i put that snippet from steve???, and how do i call it??? thanks!
Hello,
I don’t think Paul’s question was answered and my questions goes in a similar direction.
Is there a way to get the image data from the FileReference object? Or is there another objet that would allow me to?
The reason is, I would like to covert the image data to a bitearray and send it with other information to AMFPHP as a remote Object.
I’ve been looking around for an example or tutorial that would come close to this but I can’t find one that actually show how to get the user to load (import) the image in my flex app. from a filebrowser like component.
Any help would be greatly appreciated.
Thanks
-Alain
Paul,
I don’t think this is possible without a server round-trip. You’d have to get the user to select a file on their computer, upload that file to a webserver using ColdFusion, PHP, ASP, Java, etc, then download the file and display it in the RichTextEditor control. Then, to save the file locally you would probably would need to send the contents of the RichTextEditor to a server and call FileReference again to save the file. The Flash Player does not allow direct file access from an online Flex application to the user’s hard drive for editing and saving files directly. If you were building a desktop application, you could do this in AIR though.
Alain,
Similarly, you’d have to use the FileReference object to have the user select a file from their operating system. Next, you would need to upload the file to a server to save the file and then redownload the image and get the image data that way (for the same reasons as above, Flash Player doesn’t allow for immediate data access without sending the data to the server).
You may want to ask the same question on a high traffic list like FlexCoders and see if anybody else has any clever solutions or workarounds.
Peter
Thank you for the quick response Peter. I will try your suggestion about the FlexCoders list.
You have a great site by the way. Keep up the good work!
-Alain
Can any one help me out with file uploading. I have written a MXML to upload the file using file reference object. This calls the JSP to upload the file. This seems to work on windows for tomcat 5.5
If i do the same thing on linux I am getting io error 2038. Dont seem to understand the reason for it cause the windows and linux tomcat configuration is the same.
Please advise !!!!
io error 2038 on Tomcat 5.5 on Linux,
Can you file a bug at https://bugs.adobe.com/flashplayer/ and include a simple test case.
Peter
Hey guys. I’m trying to upload files using JSP as a server-side upload handler, and I really appreciate the contribution on how to do it with JSP.
But I’m having a problem, every time I try to upload something the browser keeps telling me about the error#2038 I/O error, and I’ve tried with Explorer and FIrefox and still nothing.
I’ve read a lot about why this could be happening and it seems that the server I’m running this (which is Tomcat) has a mod_security enabled option. So please I’m begging for help, I don’t know what to do. Is there a way to disable mod_security in Tomcat? Or is it something else the problem with the error code #2038?
Thanks in advance for any replies.
The FileReferene.upload doesn’t work !!! It work only if you use IE on windows, in any other Case nothing append (no error )
https://bugs.adobe.com/jira/browse/FP-78
Hi all,
I have a problem uploading files from Mac OSX using a similar method.
All is fine on Windows on any browser.
All is fine on OSX as long as my files that I want to upload don’t have spaces in the name.
Does anyone know how to get round this problem?
Or do I have to check the filename the user wants to upload and if it has spaces in tell them to rename the files because Adobe can’t get their act together!
Also are any other characters illegal in the filename only on OSX but I hear the same problems on linux also.
Actually i have designed a flex page . Now i want to have a browse button on the page which takes the path of an image to be uploaded from my local disk and when i click upload it displays it on the same flex page(may be in a text area) . Plz help??
In the above example if i have a SWF or file upload URL and that to i want to upload files in my server only
will u plzzz reply with that code
waiting for u r reply
thanks and regrads
G.vinay kumar
Ghoom solutions
Hyderabad
Thank you
Hi. What would i have to do if i wanted to upload it to a directory in my local drive.
What would i put in place of
private const FILE_UPLOAD_URL:String = “http://www.YOUR-WEBSITE-HERE.com/fileref/uploader.cfm”;
And one more thing. Where does it get stored. What exactly is stored in the .cfm file.
i uploaded it to a remote server here is the link
http://free.calypsohosting.com/sam2214/testUpload.html
When it displays completed. Where is it stored?
Sam,
I believe you can only upload files to a web server, not your local drive (unless of course your local computer had a web server installed and running).
You can see the contents of the .CFM file in a previous comment; http://blog.flexexamples.com/2007/09/21/uploading-files-in-flex-using-the-filereference-class/#comment-2777
And when it displays “completed”, the file would be stored wherever you specified in the <CFFILE /> tag.
Peter
Peter this was a great article.
I was wondering how to go about taking this a step further and writing to a XML file after each upload.
Just basic information like name, extension, type etc. I know how to access all that, but what I’ve written for the actual writing of the XML file part seems to slip up. I know how to read from an XML file into flex, but writing out to one is giving me the issue. Any ideas/help?
Thanks
Decided to go with server side XML file writing. ;) Works like a charm
Hi, i’ve got another problem. I need to create a real-time graph application, does anyone have an example? The graph should increase on the x axis each tick. Anyone has any idea?
Hello everybody!
I’v learn about Flex and server-side techologies less then month ago. I’ll be very glad, if somebody, step by step, describes me how can I force my Flex application to upload generated-in-time file to TomCat server using some Java technologies…
Thank you!=)
Hi all!
I have a problem with Upload file with FileReference.
I want to get path of file which i browse from client.
But i can’t get it!
Everyone can help me in this case, please!
Thanks for reading my problem.
Mai Ta,
I don’t believe that Flash Player returns that information (possibly for security reasons).
You could try searching for a bug/enhancement in the public Flash Player bug base at http://bugs.adobe.com/flashplayer/. Feel free to file a bug/enhancement if one doesn’t already exist. If you post the bug number here a few of us can vote and/or subscribe.
Thanks,
Peter
Hi Peterd!
Thanks for your reply!
So do you have any resolve for my problem?
I really need to get this path file for my project.
I don’t see any examples for this problem.
Sorry because of my problem!
Thanks,
Mai
Mai Ta,
I am not aware of any solutions or workarounds for this problem.
You could try asking on FlexCoders or some other list with lots of traffic and see if anybody has any ideas, but as far as I know, it is not possible to get the full path of a file when doing a file upload with the FileReference class and Flash Player.
Sorry,
Peter
Hi Peterd!
Thanks for your help very much!
Maybe i will change the way to upload file in Flex or only get file name in my project.
Thank you so much!
Nice day to u!
Thanks,
Mai
hi! petered!!
I can’t get xml string encoded by euc-kr when UPLOAD_COMPLETE_DATA event is occured.
I checked correct xml string on html, tomcat logs.
But only in Flex, xml string was bloken.
Plz help me ~~~ lol.
ps. There is no problem with HTTPService request/response.
public function fileRequest(url:String):void
{
var urlRequest:URLRequest = new URLRequest(url);
urlRequest.method = "POST";
file.addEventListener(DataEvent.UPLOAD_COMPLETE_DATA, fileResultHandler);
file.upload(urlRequest,"FileData",false);
}
--------------------------------------------------------
HTML, Tomcat Log
--------------------------------------------------------
테스트1
01000000001
abc1
--------------------------------------------------------
FLEX
--------------------------------------------------------
źƮ1
01000000001
abc1
euni,
Sorry, I don’t know why that would happen with euc-kr. Can you file a bug at http://bugs.adobe.com/flashplayer/ and attach any source code or files you think are relevant and somebody on the Player team may be able to have a look.
Peter
Hi
I’ve been trying to make this work using java spring as backend. But I can’t make it work. Spring has an implementation for file upload and Im using that as my backend.
Anyone out there got any idea how to do this?
Thanks :D
Hi Peter, how can i prevent the SecurityError: Error #2148: when i’m uploading files from my local desktop to an outside-the-sandbox-server. I tried a lot of hacks (crossdomain.xml, Security.allowDomain, eg) but this error, everytime appears. But the funny thing is, that the upload is complete, but i didn’t get any data from the server, that gives succes. Locally with localhost everything works finest.
Sorry Peter, just ignore my last comment - it was not the fault of the filereference, but i did something wrong with the data that was sent from the server
I am working on an AIR app. that records videos, using RED5. Once the user is happy with a video the app uploads the flv to a Windows server.
It works fine for short videos (small files), but when the file size is larger (I don’t know the threshold) it does not work anymore.
Do you know how to allow the app. or the asp.net script to work with large files?
Thanks.
I try to to upload a image to a server, but often the images are huge and I need to resize them before I upload them. Is there a way for flex to do this on the client side so I don’t have to uploade 20mb and then resize it.
Help or an example is preciated.
Regards
Ronny
Ronny,
I’ve never tried resizing images/BitmapData before uploading it to a server-side script.
You may want to try asking on the FlexCoders mailing list and see if anybody there has any suggestions.
Sorry,
Peter
greets,
nice blog ;)
I have a question about that fu… ahm nice ;) file upload feature after messing around with it a few ours long. So, here my prob: I’m using the aspx and I’ll say it’s working. I set all the events I need but in that special case the httpStatusEvent says nothing, only the openEvent stucks on [Event type=”open” bubbles=false cancelable=false eventPhase=2] progress bar says it’s ready but there is no file in the directory (and yeah I set allready all the rights to that spec. dir.)
Somebody an idea?
thanks a lot.
jimmi
I’m trying to upload files and it works great in Windows, but on OS X it doesn’t ever hit my URLRequest page. Is there any insight on what is different between the two, or something I need to do in for OS X?
Hi Everyone,
Can any one help me to convert any type of Video files into .flv format (i.e) flash video format.
I mean, if we browse and select any type of video, it (Flex Program) should convert it to .flv format.
Thanks in Advance……