Uploading Files with Flex and PHP
Dustin and I have had the chance to do some Flex applications for our employer over the last few months, and we thought it would be helpful to share some of the things we've learned.One of the things that we needed to accomplish in both our Flex applications was the ability for the user to upload files to the server. Of course, Flex by itself can't upload and post files to a server without the help of a server-side script. We used PHP.
Check out a quickly-developed Flex application that manages multiple file uploads and processes them through a PHP file (right-click in the application to view the source). Or, you can check out an explanation and strategy we used for the PHP.

58 Comments:
I post a sample php and as3 (no mxml)
http://not-equal.blogspot.com/2006/08/upload-file-as3-php.html
As all the examples of file upload with flash/flex I can see, there is the same probleme: there is no listener of the response of the server script (php here): the onUploadComplete function return True because there is no HTTP error during tre transaction.
In your example there is a Parse error in the php script but the flex apllication said: OK.
A solution we find is to generate HTTP response instead of return True, False and sone error Text that is no listen by flex. Example could be see at http://web.infostrates.fr/infolabs/index.php/erazor
Stephane
I didn't make the PHP functional because of obvious security purposes. The upload Flex example doesn't listen for the XML feedback, but that is what we usually use to determine if the file was uploaded successfully or not. I fixed the parse error :-)
is there a way to do drag and drop in flex 2 and as3?
Yes, it's not too bad. Instead of accessing the events directly from the MovieClip like in AS 2, now you add event listeners to give the drag and drop capability to a MovieClip or Sprite. Here's some sample code that would go on the first frame of a movie with a MovieClip called "ball" on the stage.
ball.addEventListener(MouseEvent.MOUSE_DOWN,downHandler);
ball.addEventListener(MouseEvent.MOUSE_UP,upHandler);
function downHandler(evt:MouseEvent) {
ball.startDrag(false);
}
function upHandler(evt:MouseEvent) {
ball.stopDrag();
}
I haven't figured out a good way to do "onReleaseOutside" yet, anyone have any ideas?
Good example! A couple of weeks I posted an example on how to perform Multi-File Uploads with Flex and Coldfusion. My example will also work with a php script to handle the uploaded files check it out http://ryanfavro.newmediateam.com/blog/index.cfm/2006/8/12/Flex-2-Multi-File-Upload-Example
So, how do you 'get' the HTTP response from the PHP return string in the Flex app?
I see the return statement in the PHP script, but there is nothing in the Flex application that would listen for the values.
Could you give us a glimps into how you did it?
Thanks,
JB
Excellent script! I've been trying to port it to my personal site so that my friends can upload their own images but I keep getting an error msg when I try to upload: "security error in uploading file"
I used the PHP script you provided but still can't seem to get it to work. Thought it might have to do with the CHMOD settings at first but no. I'm a novice programmer, so any help is greatly appreciated!
I tried to do the same thing in my project, but the php script isn't able to read the retrieved request data (as action, file name, etc.). There is some configuration that allow connection from flex to php?
Thanks
Valerio
I tried to do the same thing in my project, but the php script isn't able to read the retrieved request data (as action, file name, etc.). There is some configuration that allow connection from flex to php?
Thanks
valerio
Communication between Flex and PHP is much like any form or webpage with another. The PHP depends on variables that get passed to it via methods, such as POST and GET. In the sample script, if the PHP is getting either a POST or a GET variable of "action" with a value of "upload" (that's why we used $_REQUEST, it looks at both), then it starts the upload.
You should be able to set POST as the method in Flex on the URLRequest object.
Maybe there's some miss line in my code. Here the lines in to flex code that make the upload operation:
private var fileUp:FileReference;
private var fileUpList:FileReferenceList;
private var sendVars:URLVariables;
private var request:URLRequest;
...in..init()...............
sendVars = new URLVariables();
sendVars.action = "upload";
request = new URLRequest();
request.data = sendVars;
request.url = "http://localhost:8086/flex2/interfaccia1/upload.php";
request.method = URLRequestMethod.POST;
............................
private function clickUpload(event:Event):void{
fileUpList = new FileReferenceList(); fileUpList.addEventListener(Event.SELECT, selectHandler);
fileUpList.browse();
}
private function selectHandler(event:Event):void {
fileUp = new FileReference();
fileUp = fileUpList.fileList[0].data;
trace(fileUpList.fileList[0].name);
fileUp.addEventListener(Event.COMPLETE, completeUploadHandler);
fileUp.upload(request, "file", false);
}
The php script is quite the same.
very great code! thanks you!
i complete it with a php class, if you want it, take it!
Class here !
How would you add a filter to the php code to ensure that only permitted file types (e.g. jpeg, gif, png) are uploaded?
Well I don't know about PHP, but I know in flex you can set specifications of what filetypes appear in the browse window:
add this line at the beggining of the code in Flex:
private var imageTypes:FileFilter = new FileFilter("Images (*.jpg, *.jpeg, *.gif, *.png)", "*.jpg; *.jpeg; *.gif; *.png");
And change this line:
_refAddFiles.browse();
To:
_refAddFiles.browse([imageTypes]);
I have my own problem though, I'm trying to combine this script with other image resizing php scripts, but whatever I try never works. I'm a noob when it comes to PHP, so please help.
Very impressive! well done.
You will get a security error if you add a www in front of your url..
http://www.codycodingcowboy.cahlan.com/files/file_uploads/FileUpload.html
i got whats the problem, dont know how to correct it.. The problem is because you specified the php file path without using www.
Hi Cahlan,
any idea about how can I correct the www bug?
Anz
Anz--
Could you clarify what you're trying to do? Are you trying to implement the source on your own domain? If so, you have to change the url references in the Flex source to match your domain.
Cahlan
I am having problems getting my flex app to be able to access files on the local machine for upload. I cannot get past the security error:
SecurityError: Error #2148: SWF file http://www.ourdomain.com/uploader/uploader.swf cannot access local resource file:///C:/vor/sedona_ball_drop/images/7_canyons_logo.jpg. Only local-with-filesystem and trusted local SWF files may access local resources. at ....
I tried the compiler flag:
-use-network=false
to no avail.
I'm really puzzled how you got your app to work - I saw your code:
private function initApp():void {
Security.allowDomain("*");
_arrUploadFiles = new Array();
}
and tried to add the:
Security.allowDomain("*");
to my code.
this didn't help.
any ideas?
Hi All,
Can you share me the Flex project files?
Thanks a lot,
TP.
Hello, every body.
I have set up mxml and php on my web server. It runs and its result is:
Upload Successful
File(s) have been uploaded
But I haven't seen any real file uploaded on my web server. Why? Pleae help me for solving it. Many thanks
I haved a security problem but I can solved it writing the correct path in _strDomain and _strUploadScript.
I hope some problems that you have, may be solved whith this.
My English is bad. I hope you understand what I mean.
Javi.
Great script. I have been searching for a way to name a file on the server based upon what someone has filled out in the Flex form. For instance, if they upload a file and upload it, I want it to be called whatever their first name is based on a textfield feature. I can't figure how to send any other data to the php and or asp page except the file itself. Any thoughts?
This Script works fine execpt i can get any information from php script for example if files already exists in directory. How do i fix this ?
Very nice, although I am having the same problem as Anh Nguyen Ngoc up above. I will see the file is selected and the upload completes, however, when I look in the destination folder the uploaded file is no where to be found.
The php script is correct I'm pretty sure, a similar one is working for a non-Flex application.
Has anyone run into this problem and found a solution, or have any ideas? Thanks in advance!
same problem here... all looks good except no file uploaded! STEF
I've been trying to use the example on your server (not trying to use the code, but actually hitting your page at http://weblog.cahlan.com/files/file_uploads/FileUpload.html). Every time I try it, I get a security error: "Security Error in uploading file."
Has something changed on your server or in the Flash Player that has made your example not work?
Unfortunately, we have disabled much of the example's functionality due to multiple attacks on our server. Nothing was damaged or compromised, but enough attempts were made to prompt us to disable the script completely so that hackers wouldn't eventually succeed.
Pretty sad when something that is meant to be free and useful is exploited like this.
Hi, can you share only PHP source file? Thanks a lot!!!
Uploading with PHP is fairly simple, as long as your PHP and server settings allow it. The following code would take a file named "file" in the form and upload it.
$file_temp = $_FILES['file']['tmp_name'];
$file_name = $_FILES['file']['name'];
$file_path = $_SERVER['DOCUMENT_ROOT']."/myFileDir";
//checks for duplicate files
if(!file_exists($file_path."/".$file_name)) {
//complete upload
$filestatus = move_uploaded_file($file_temp,$file_path."/".$file_name);
if(!$filestatus) {
//error in uploading file
}
}
Ok, thanks! But I still have the IOError #2038 problem. I tried on localhost server and everything works good, but when I change parameters in FLEX (for the real webserver), comiple and deploy onto the server I encounter this error. The folder where I work has got 777 permissions. I tried also with a crossdomain.xml policy or with .htaccess file to disable security controls (as someone said in other blogs), but nothing solved the problem...
The path of my upload.php is correct and the script is sintax-correct too and it works on localhost!
My Flex application starts uploading files and after 1-2 seconds they are completed I receive the IOError #2038. Someone said also that it could be in the MIME type of the upload (but why does it work on localhost?). Does someone suggest me a solution? Thanks!
Hi,
finally I found the real problem: doing some HTTP logging I discovere d that it's an HTTP 403 error. The problem is that Flex has a small bug in transfering files (you can find it in Adobe docs), because it tranfers with "final boundary missing" in MIME request. So if you have an ISS with Linux Server you should try to set .htaccess file adding this 2 lines:
SecFilterEngine Off
SecFilterScanPOST Off
Then if you have an ISS with strong security policies as mine [aruba.it] (for example you cannot put these lines into the .htaccess file) you can't run properly your application... I'm still trying to find out a new solution, but I think I should unfortunately choose another technology...
Hi, thanks for your code. I copied your php and flex and changed the url to localhost it all says it uploads successfully but where does the file go to? Is there something I have missed?
Cheers,
Rob O.
Hi, found the problem. I changed the reference in the php file from myFileDir to files (the same directory that the upload.php file is in and then gave iusr_machinename read and write access to this directory. Strangely I was given no security error when the iusr_ user had no access to the directory just a message to say that upload was successful.
Hi, I do have to say that this is a wonderfull script we're having here, but the PHP code provided alongside is not meant to work at all...
When you submit the form, eventhough we can read (in the FileUpload.mxml file) :
...
var sendVars:URLVariables = new URLVariables();
sendVars.action = "upload";
var request:URLRequest = new URLRequest();
request.data = sendVars;
...
there's no "action" parameter passed alongise with the Form. Therefore, the Switch statement has no way of working in the PHP script that handles the upload process.
The only 2 parameters passed are "Upload" and "Filename".
Hi again,
I finally found why the URLVariables parameters wouldn't be passed alongside with the form.
In FileUpload.mxml, you should change
request.method = URLRequestMethod.POST;
by
request.method = URLRequestMethod.GET;
Then you'll be able to play around with the $_REQUEST['action'] parameter provided within the php file that handles the upload onto the server.
Cheers,
Luc.
Hi, still there is no file uploaded.
whats wrong with the php. some details are missing in how to configure the php file...
$file_temp = $_FILES['file']['tmp_name'];
$file_name = $_FILES['file']['name'];
$file_path = $_SERVER['what goes here']."/what goes here";
//checks for duplicate files
if(!file_exists($file_path."/what goes here".$file_name)) {
//complete upload
$filestatus = move_uploaded_file($file_temp,$file_path."/what goes here".$file_name);
we want to view the upload component working... thanks
You are probably going to need to look at your php.ini file. Since there are so many different kinds of configurations and setups for file uploads, we didn't want to get too specific. I would also advise trying file uploads with your server with just straight HTML and PHP so that you are sure that your PHP file uploads are working.
Check your php.ini file for the file_uploads variable to make sure it is enabled. Also check the upload_tmp_dir and make sure that whatever dir. you choose has read/write access. Again, doing a straight HTML PHP file upload will clear up a lot of problems before starting to try and implement Flex.
Hi,
what object on Flex side contain this returned from php success/failure xml so it can be examined? I can't find it in the sample app. Thanks.
If you search this blog for the file upload component, you'll find a lot better example for uploading files withe Flex. The event listener you're looking for in order to listen for responses from the PHP upload is DataEvent.UPLOAD_COMPLETE_DATA.
So it would look something like this: myrequest.addEventListener(DataEvent.UPLOAD_COMPLETE_DATA,myFunction);
You can get the return from that DataEvent, look it up in Flex and you'll see where.
I believe the issue is that the Flex upload object is always "Filedata"
not 'file' as in this example:
$file_temp = $_FILES['file']['tmp_name'];
$file_name = $_FILES['file']['name'];
try
$file_temp = $_FILES['Filedata']['tmp_name'];
$file_name = $_FILES['Filedata']['name'];
I'm testing this script on my server (Linux/Apache), and I've found that it works well as long as the files are smaller, say, 1.5MB or less. I tried uploading a couple of 2+ MB JPEG files, and I get the same error others have described -- Flex says the upload completes, but the file doesn't show up on my server. Could this be an issue with how my PHP is configured?
Any help is appreciated.
@Chris
The difficulty is probably in your PHP configuration. Check your php.ini file for the upload_max_filesize and post_max_size settings.
I am a web host reseller, and since I don't own the server on which my sites are stored, I don't think I have access to the php.ini file. Does this mean that I'm outta luck?
Alternatively, I've read a few posts on some other forums about using PHP-based FTP, which supposedly bypasses the file size restrictions in the php.ini file. Have you ever heard of this kind of workaround?
Has anyone gotten a successfully set up PHP file that actually takes the Filedata from the flex app and moves the file to a directory? I am stumped here.
Since PHP file uploads are a different beast entirely, I recommend following some PHP tutorials for setting up a simple file upload with an HTML form. That way you know the file uploads are working before you try to add Flex into the equation.
The cryptic nature of the comments and responses here nearly completely invalidate this source as a learning tool. Why not explain things?
@Chad U
This post was meant to be a help for Flex developers wanting to upload files through Flex and PHP. It isn't a tutorial. The problem is that there are a myriad of things that could go wrong with your server, PHP configuration, and file uploads before you even get to the Flex. I'm sorry, but I simply don't have time (nor would I be the best source) to explain everything that accompanies how to handle a file upload in PHP. There are a ton of better tutorials and resources out there for that. Otherwise, I would spend a good portion of my week responding to comments on here on a case-by-base basis, because that would be the only way to debug every application of this out there.
Here are a couple links I found to get you started:
http://us3.php.net/features.file-upload
http://www.tizag.com/phpT/fileupload.php
I'm sorry I can't be of much more help. I hope the Flex code can still be useful to you once you get your uploads working.
Hi,
Thanks for sharing this.
Has anyone succeeded in doing a file upload with Flex over HTTPS using Firefox?
Thanks, Gerry
I get an IO error? Any idea on what it can be?
I've changed the paths to my domain, and the upload dir has read/write access...?
I also get an IO error... but i found some sources that indicate there is an error in file upload on MAC... my colleauges using windows can use the spin-off from this example just fine...
hmmm...
adobe update anyone?
Hi,
I am getting following error.
1046: Type was not found or was not a compile-time constant: winProgress. FileUploader.mxml
Earlier this script worked fine but now it is giving me this error on following line:
private var _winProgress:winProgress;
Please help.
Regards,
Ranjan
where is the sourcecode of the Flex project????
I'm having problems getting files onto my server using adobe flex and php.
As it stands my application will prompt the user to select a file, when the user selects the file it displays the following error,
Error #2044: Unhandled IOErrorEvent:. text=Error #2038: File I/O Error.
at app/upload()
at app/___Button1_click()
The flex app links back to an upload.php page which handles the file and transfer it to the server, the odd thing is that it works fine locally but not online, I have changed the permisson on the folders but still no joy. I'm wondering if anyone could shed any light or provide a link to a flex file upload tutorial that works.
Thank you
For those with the error text=Error #2038: File I/O Error.
Make shure you have set the upload folder to 777
And add these line of code to your php.ini:
------------------------------------
upload_max_filesize = 1024M
post_max_size = 1024M
short_open_tag = on
------------------------------------
how to post those files to new window?
i have an existing flex and want to add this to it. being fairly new to flex 1+ yr, is there a way to wire this in? i need details.. thanks.
Post a Comment
Links to this post:
Create a Link
<< Home