Asynchronous File Upload with PHP, Javascript & iFrame
This is a tutorial create from a modification of Asynchronous image file upload without AJAX by Martin Konicek. The original sources code by Martin Konicek only focus on image upload so I'm going to take in another step forward so that you can use it for any file type.
Asynchronous File Upload with PHP Javascript iFrame
As you can see from the picture above, in the end the file upload would be something almost similar to GMail attachment and it can be modify to met any additional requirement you might need. Today I'll be teaching you how to develop it using database file upload (other option would be physical file upload which has been covered in the original sources code).
Let first see what is needed to display the application, let name the application display page as index.php. Here the code that you need to add.
CSS
Add this inside the <HEAD> tag.
<style type='text/css'>
iframe {
border-width: 0px;
height: 60px;
width: 400px;
vertical-align:top;
}
iframe.hidden {
visibility: hidden;
width:0px;
height:0px;
}
</style>
The Display
You can add this in any manner you wish to have it, but please remain <DIV id='list'> alone as it is.
<table>
<tr>
<td>Attachment</td>
<td>
<div id='iframe'>
<iframe src='upload.php' frameborder='' scrolling='0'></iframe>
</div>
<div id='list'></div>
</td>
</tr>
</table>
That just about it for index.php. Now let see the real magic of this application. As you might have notice from the iframe sources code the file that we be using to upload the file is upload.php. I have divided it into three (3) part which is PHP Upload Script, Javascript Upload Script and Form to make it easier for you to understand it.
PHP Upload Script
In this part, it almost similar to Uploading Files To MySQL Database tutorial. You might want to read on that if you feel lost.
<?php
@$ftmp = $_FILES['image']['tmp_name'];
@$oname = $_FILES['image']['name'];
@$fname = $_FILES['image']['name'];
@$fsize = $_FILES['image']['size'];
@$ftype = $_FILES['image']['type'];
if(IsSet($ftmp)) :
$fp = fopen($ftmp, 'r');
$content = fread($fp, filesize($ftmp));
$content = addslashes($content);
fclose($fp);
// include your database configuration & connection
$new_file_name = time()."_".$fname;
$query = "INSERT INTO file_upload (name, type, size, content)
VALUES('".$new_file_name."', '".$ftype."', ".$fsize.", '".$content."')";
$result = mysql_query($query);
$file_id = mysql_insert_id();
?>
<!-- Copy & Paste "Javascript Upload Script" -->
<?php
exit();
endif;
?>
<!-- Copy & Paste "Form" -->
Javascript Upload Script
This is the code that going to make the uploaded file appear in index.php under <div id='list'>. The listed file would also have an hidden input name filename[] so you can manipulate it afterward.
<html><head><script>
var par = window.parent.document;
var list = par.getElementById('list');
var fileid = par.createElement('div');
var inpid = par.createElement('input');
var imgdiv = list.getElementsByTagName('div')[<?=(int)$_POST['imgnum']?>];
var image = imgdiv.getElementsByTagName('img')[0];
imgdiv.removeChild(image);
list.removeChild(imgdiv);
fileid.setAttribute('id', 'upfile<?=$file_id?>');
fileid.innerHTML = '<?=$oname?>';
inpid.type = 'hidden';
inpid.name = 'filename[]';
inpid.value = '<?=$file_id?>';
list.appendChild(fileid);
fileid.appendChild(inpid);
</script></head>
</html>
Form
This form will automatically upload a file oned you selected a file.
<html><head>
<script language="javascript">
function upload(){
// hide old iframe
var par = window.parent.document;
var num = par.getElementsByTagName('iframe').length - 1;
var iframe = par.getElementsByTagName('iframe')[num];
iframe.className = 'hidden';
// create new iframe
var new_iframe = par.createElement('iframe');
new_iframe.src = 'upload.php';
new_iframe.frameBorder = '0';
par.getElementById('iframe').appendChild(new_iframe);
// add image progress
var list = par.getElementById('list');
var new_div = par.createElement('div');
var new_img = par.createElement('img');
new_img.src = 'indicator.gif';
new_img.className = 'load';
new_div.appendChild(new_img);
list.appendChild(new_div);
// send
var imgnum = list.getElementsByTagName('div').length - 1;
document.iform.imgnum.value = imgnum;
document.iform.submit();
}
</script>
<style>
body {vertical-align:top;}
</style>
<head>
<body>
<form name="iform" action="" method="post" enctype="multipart/form-data">
<input id="file" type="file" name="image" onchange="upload()" />
<input type="hidden" name="imgnum" />
</form>
</html>
Indicator Icon
Right click as save (save as target...) the following image file.
indicator.gif →










» mjuneja@gmail.com:
on 26-July 2006 at 19:21 PM | Quote
Thanks for the tip. I found it very useful.
» tomas:
on 07-September 2006 at 04:55 AM | Quote
Great !
For infos, futures web API (after XMLhttpRequest) will concern drag and drop, upload file and much more ... That will probably make it easier.
WebAPI
» Angels:
on 07-September 2006 at 15:30 PM | Quote
Thanks for sharing your script. Finally something which does work and doesn't need a cgi/java-wrapper class for progress display (which i don't need).
I ran into some trouble debugging: I switched off the mysql part, with error_reporting fully enabled $file_id contains a "notice" error string which breaks the javascript output completly.
crynobone:
on 07-September 2006 at 16:01 PM | Quote
I would like to see the error if possible. The script is not really a complete script where I have left room for customization for developer to really go into detail what they want the uploading function looks like.
» Jerre:
on 28-September 2006 at 20:56 PM | Quote
I'm using the script that you axplain abouve...
But my problem is that he doesn't find the file. So all @$ftmp = $_FILES['image']['tmp_name']; and ... are empty.
crynobone:
on 28-September 2006 at 21:22 PM | Quote
An error like that only occur when you send/submit the file upload request to an invalid file, in the example it will send the request to the same file, so make sure you name the file inside the iframe as upload.php, what would be my diagnosis based on your explanation.
If it isn't the culprit I hope you can gave more explaination to your problem in future.
» Jerre:
on 28-September 2006 at 21:29 PM | Quote
thx for the fast answer, but I found an sollution. I was woking offline on a virtual php server, but once i uploaded the files online, it was working. So thanks for the code!
crynobone:
on 02-October 2006 at 11:59 AM | Quote
I have make some modification to the script. Everything now is done via JavaScript DOM instead of using innerHTML.
» Roland:
on 13-November 2006 at 04:23 AM | Quote
Cool script but there is an error:
In the Java Upload script:
var imgdiv = images.getElementsByTagName('div')[<?=(int)$_POST['imgnum']?>];
'images' needs to be replaced by 'list' (I guess you forgot)
i.e.
var imgdiv = list.getElementsByTagName('div')[<?=(int)$_POST['imgnum']?>];
Otherwise collio :-D
crynobone:
on 13-November 2006 at 08:18 AM | Quote
Thank for the notification. Really appreciate it.
» ssdesign:
on 22-November 2006 at 15:30 PM | Quote
I get a parse error on this line:
<?php
exit();
}
?>
Parse error: parse error, unexpected '}' in C:Program Filesxampp.....
Any idea what i might be doing wrong?
Thanks.
crynobone:
on 22-November 2006 at 15:44 PM | Quote
Sorry about that, You can either replace '}' with 'endif;' without the '' or change 'if(IsSet($ftmp)) :' to 'if(IsSet($ftmp)) {'
» tstrokes:
on 07-December 2006 at 05:58 AM | Quote
Shouldn't this line - inpid.value = '<?=fileid?>'; - read - inpid.value = '<?=$file_id?>';
Also is there anyway I could adapt this to make the files stay in the list after a reload.
-tstrokes
» JJ:
on 07-December 2006 at 06:48 AM | Quote
All i get is the progress wheel spinning...nothing uploads. also, no temp/image files located tmp or upload folders. Ideas?
Thanks,
JJ
crynobone:
on 07-December 2006 at 07:54 AM | Quote
Thank for the sharp eyes.
Well yes but you need to add another field in the database, maybe a row called 'temp' where completed process will be marked as 1 else it would be marked as 0 (uncompleted assignation). Using these you can query the database for uncompleted assignation by adding all marked as 0 into the container id=list.
May I know the some detail including file size, database uploading/filesystem etc.
» heny:
on 30-December 2006 at 16:31 PM | Quote
Nice article, It took me sometime to find something that can work like gMail attachment.
» satya prakash karan:
on 27-April 2007 at 19:21 PM | Quote
Thanks!
At least it is working. I was looking for webtoolkit like file upload but that is not working.
Thank You!
» katun:
on 06-August 2007 at 19:00 PM | Quote
i think you people are realy crazy!
i never see something more strange.
is very hard to read this tutorial.
kiss principle (keep it simple, stupid)
crynobone:
on 07-August 2007 at 01:27 AM | Quote
So why are you here?
» clark inthedark:
on 07-August 2007 at 13:56 PM | Quote
Hello... I'm a beginner. Help. :)
This is exactly what I've been looking for. Everything works fine: I can choose a file and it uploads it into the mySQL database. Only problem is that the indicator.gif shows and it never changes to anything else after the upload.
My environment: testing on mac os 10.4.10, php 5.2.2, apache 1.3.33, will implement on IIS, windows 2003 server.
My wish: 1. to upload and have it list what it uploaded. 2. Upload file to directory, but create record of upload in the database (#2 I think i can handle.. it's #1 I'm having problems with).
Thank you for putting this together! You're awesome!
» Josh Shand:
on 15-August 2007 at 11:25 AM | Quote
Hey there,
I really like the look of this script and I've been trying to implement it so that it uses a whole file upload (as the original) but then displays a list as in your version. So far I can get it to upload the file etc. But the indicator icon just remains instead of becoming a list of the files. Would you be able to drop me an email about this?
Cheers
» sohail:
on 25-August 2007 at 00:23 AM | Quote
This exactly i was looking for to incorporate in my email form, but some strange reason, I don't know why i am getting this error, can someone help please. This is the erro code i got in firefox below:
Error: "var imgdiv = list.getElementsByTagName('div')[<?php"=(int)$_POST['imgnum']";?>];"
crynobone:
on 25-August 2007 at 11:39 AM | Quote
<?phpand<?=can't be mixed together, you can only use either one method, if you insist to use<?phpjust atprintin your code because for example<?=$str;?>is equal to<?php print $str; ?>.So the right way to write the code is
var imgdiv = list.getElementsByTagName('div')[<?=(int)$_POST['imgnum']?>];» lazarus:
on 01-September 2007 at 19:00 PM | Quote
Hey there,
thanks for this, i really like it.but i can't modified it for uploading single file (delete the previous image box when i upload a new image)
Thank you for you help.
crynobone:
on 02-September 2007 at 08:24 AM | Quote
You can do that by deleting these following line:
// create new iframevar new_iframe = par.createElement('iframe');
new_iframe.src = 'upload.php';
new_iframe.frameBorder = '0';
par.getElementById('iframe').appendChild(new_iframe);
» lazarus:
on 12-September 2007 at 07:55 AM | Quote
hi,
How can i use it in the form with submit to.
tks.
» Rupesh:
on 22-September 2007 at 19:01 PM | Quote
Hi
Can Any one Explain
In ASP.NET How to Upload FIle without <input type="file"> tag
is there any way to upload the FIle
» Bart:
on 25-September 2007 at 02:40 AM | Quote
I made something similar myself, but when I try to include in the iframe, it simply shows the source code starting after the first html tag.
So basically I have something like this:
<?php
//some code
...
//a variable that contains an html tag:
$tag = "<img src="$file" class="some_class">";
//some other code
...
$html =<<<EOHTML
<html>
... (including the form)
</html>
EOHTML;
echo $html;
?>
What I see in the iframe is literally this:
[the 'image']";
//the other code
...
$html =<<<EOHTML
//the rest of the page
...
EOHTML; echo $html; ?>
When I open the php file in a separate window (thus not included in an iframe) everything works fine.
Does anyone know what's the problem?
» bonesxtr:
on 10-October 2007 at 21:47 PM | Quote
$tag = "<img src="$file" class="some_class">";
Need to escape backslashes.
» cube:
on 01-January 2008 at 23:02 PM | Quote
Hi Crynobone!
Many thanx for sharing your script. It's really great.
But, how can i include it in another php script in an iframe?
My Problem:
I have another php-script with a form and i would like to include an iform in that so, that i could load your script in my.
I had tested it in 2 ways, once as "stand alone" and once in my own script.
In "stand alone" mode it works fine but in my own skript it loads the list with my included datasets and lets me delete datasets. But i could not insert new files to my mysql database, because request to the javascript-function "upload()" does not work. I could not understand why.
Do you have any tip how i could solve the problem ?
Thank you for your help.
» cube:
on 03-January 2008 at 05:45 AM | Quote
I have modify the script and add a delete link, to delete a choosable dataset in the list. Its great!
» cube:
on 03-January 2008 at 05:47 AM | Quote
aahh....i forgot.....wish you a happy new year!
» cube:
on 03-January 2008 at 05:51 AM | Quote
How can i add some new variables as i.e. varchar to the Insert statement?
My variables could not identified by the insert statement :-(
how can i do it?
Please .. Need Help!
» eve:
on 11-January 2008 at 11:58 AM | Quote
hi, i need help~i would like to upload images using iframe on FCKeditor function.is it possible? how to make it?
crynobone:
on 14-January 2008 at 01:28 AM | Quote
Can you provide better structure, or information.
It is possible if you have the right skill.
» Andrew:
on 25-January 2008 at 02:34 AM | Quote
tight scripting. Thank you and the person you originally learned from.
» Mus:
on 03-February 2008 at 18:45 PM | Quote
Hi is it possible to have two different file uploads on the same page inside a table? I was thinking of using your great example for uploading pictures into mysql and videos on the filesystem of the server.
Oh and you script and the one you based on saved me. Thanks a lot and great job!!
» Meto:
on 05-March 2008 at 22:20 PM | Quote
I have a question.
How did the iform understand which frame to use for file upload when his action is empty
<form name="iform" action="" ... >
» Meto:
on 06-March 2008 at 03:22 AM | Quote
My mistake, target empty, how the form understand which frame to use.
» Michael:
on 26-March 2008 at 00:10 AM | Quote
How to upload a file from a client to the server without using a form (only php script)?
» akmal:
on 23-April 2008 at 15:30 PM | Quote
how to develop a text editor in PHP? can u explain with detail about it? please... tq!