Ajax File Upload

You might have seen Ajax File Uploading in some sites. The basic idea is to upload a file without refreshing the page. Some sites go even further by providing details on how much percentage is uploaded, etc. It is very easy to achieve this effect using javascript.

First off, I did not like using the term 'Ajax' when describing this method. But there is no other word that can be used. And this method fits within my definition of Ajax - "Sending or receiving data from the server without refreshing the page.". So I will name this method Ajax file upload.

Theory

The basic idea behind this effect is to redirect a form's action into a hidden IFrame. So, when the form with the file field is submitted, the result will appear in a IFrame. But since it is hidden, the user will not see it. This effect is achieved using the 'target' attribute of the Form tag.



See the small squire? That is the IFrame. Typically, it will be hidden.

Code

(X)HTML

<form id="file_upload_form" method="post" enctype="multipart/form-data" action="upload.php">
<input name="file" id="file" size="27" type="file" /><br />
<input type="submit" name="action" value="Upload" /><br />
<iframe id="upload_target" name="upload_target" src="" style="width:0;height:0;border:0px solid #fff;"></iframe>
</form>

JavaScript

function init() {
	document.getElementById('file_upload_form').onsubmit=function() {
		document.getElementById('file_upload_form').target = 'upload_target'; //'upload_target' is the name of the iframe
	}
}
window.onload=init;

PHP

This should be in upload.php - the action of the form.

<?php
include('../../../common.php');
upload('file','.','txt,jpg,jpeg,gif,png');

The code to upload the file must be given here. I used one of my custom functions to upload the file - it is not a native PHP function. Needless to say, this is not restricted to PHP - you can use any server side language here.

Update: Part two - Ajax File Upload Response Handling

Comments

Anonymous at 12 Apr, 2007 03:31
thanks for the article,
it will be interesting to see how it could give details on how much percentage is uploaded?

cheers
Reply to this.
No Average Joe at 19 Apr, 2007 06:29
Thanks so much, who knew getting this effect is so easy?
Reply to this.
Anonymous at 22 Apr, 2007 07:38
I'm a little confused why the page load logo still shows the page to be loading when uploading a file, is there anyway to upload a file without this effect?
Reply to this.
Anonymous at 25 Apr, 2007 02:40
are you sure it is AJAX? Do you know what are you saying? Because as far as I know it is not AJAX, you use frames. AJAX stands for Asynchronous JavaScript and XML, you do not do either.
Reply to this.
Anonymous at 01 Jul, 2009 09:07
you idtiot, he explained that it's not specifically AJAX, but refers to it because it asynchronously deals with data without refreshes the page, giving the same desired result as Ajax, read before you open your mouth.
Reply to this.
Fernando Franzini at 26 Apr, 2007 05:07
Very cool article !!! Help me a lot !!!
Reply to this.
Badshah at 27 Apr, 2007 05:38
I am not seeing any AJAX kind of implementation in this example. Where is the asynchronous call happening?
This is some other way to submit form. Sorry you can't say it AJAX.
Reply to this.
Jason Miller at 12 Apr, 2008 04:35
Regardless of whether using an iFrame to submit files qualifies as AJAX, it is currently the only method (in JavaScript) for submitting files to the server Asynchronously.
Reply to this.
Anonymous, but not the other Anonymous, a totally different Anonymous at 15 Jan, 2009 03:06
Jason, people are stupid, don't pay attention to them. Some don't want to code in AJAX (for example) because it's useful but because they want to get a "reward" for using a so-called sophisticated coding implementation such as AJAX.
Reply to this.
Anonymous at 05 May, 2007 07:01
Re: people complaining about AJAX, try re-reading ¶2...
Reply to this.
dwikristianto at 08 May, 2007 02:11
big thanks for article, i'll have it a try
Reply to this.
Cohen at 06 Jun, 2007 12:41
Great article, thanks!

And it is correct to call it AJAX, as AJAX 'calls' can be implemented either with XMLHttpRequests or with IFrames. In some frameworks you even get to choose which method is used to make the 'calls'.
Reply to this.
Jim at 07 Jun, 2007 11:27
Thanks friend...
Plz wud u explain a context in which this code wud be of use.
Reply to this.
Anonymous at 09 Jun, 2007 02:06
I would really like to understand how you might get the progress out of this method.
I was wondering how I might do this with httpRequest instead as well.

If someone would be so kind as to help me my E..!!(E&#($& - Mai1 is

dan ...-~~~at~~~-- danmckinnon )*)*&)* --~~~d0t~~-- net

(and of coarse ignore all the funny charecters, it's to avoid bots from grabbing my e-mail address)
Reply to this.
Bidfreelancers at 10 Jun, 2007 05:17
Bit confuse. still learning to make it work.
Reply to this.
gc at 14 Jun, 2007 06:37
how do you hide form after uploading the file
Reply to this.
Bruno at 21 Jun, 2007 06:53
Hi,
This doesn't seem to be working in IE.
Any reason for that?
Cheers
Reply to this.
Binny V A at 21 Jun, 2007 11:33
Its working on my system - which version of IE are you using?
Reply to this.
Bruno at 24 Jun, 2007 08:08
Hi,
Thanks for your reply
I'm using version 6.0
Cheers
Bruno
Reply to this.
Anonymous at 09 Jul, 2007 10:50
I'm also trying to get it to work in IE6 (works fine in Firefox) but it continues to bring up a seperate window. Only difference in code is that I create the form, inputs and ifram in Javascript. Any clues?
Reply to this.
Josh Stodola at 27 Jun, 2007 07:32
Can you explain why you used javascript to set the target of the form?!
Reply to this.
Binny V A at 27 Jun, 2007 10:28
Will not work otherwise - target is not a valid attribute for a form tag.
Reply to this.
Anonymous at 07 Jul, 2008 07:10
Not true. "target" is valid. See: http://www.w3.org/TR/html401/interact/forms.html#h-17.3 "Attributes defined elsewhere:"
Reply to this.
Anonymous at 14 Feb, 2009 07:27
I still insist, this isn't AJAX
Reply to this.
Anonymous at 06 Jul, 2007 03:49
Yes it is not ajax, File form upload and Browser compatibility are some of ajax drawback,
follow the following like you can find useful code
www.webtoolkit.info/ajax-file-upload.html
Reply to this.
Anonymous at 10 May, 2008 08:02
If you were paying attention (or know anything about JS or the DOM), the code at the link you provide does the same thing. It just dynamically creates the iframe per request.
Reply to this.
Shitesh Srivastava at 14 Jul, 2007 05:28
this is very good site
Reply to this.
yes at 24 Jul, 2007 02:45
what is this ?? you should write some thing else??
Reply to this.
Anonymous at 26 Feb, 2009 07:45
so should you
Reply to this.
Leonardo Gazio at 18 Jul, 2007 11:34
That's not AJAX, and even if so, I can't see any diferent stuff on it, when we look for ajax, we're looking for dinamic things like, showing the 'loading...' or if possible a real time progressbar...
Reply to this.
Rob at 19 Jul, 2007 01:27
If you want progress check this out:
www.seemysites.net/projFolder/uploader/

I am also not able to get any of the examples of this method (i.e. iframes) to work with IE 6. If anyone has been able to do it please post it here.
Since Ajax stands for for "Asynchronous JavaScript and XML", I have a feeling there is no way to do file uploads since JSON and XML can only work with text going to and coming from the server. I still can't find a way to send a file over using pure AJAX. Please prove me wrong if you can.
Reply to this.
Anonymous at 14 Feb, 2009 07:30
en am still waiting for it, now thats what we would call AJAX
Reply to this.
Anonymous at 23 Aug, 2007 08:02
Honestly, this is just using php function. You can access the name, size, and error of the loaded file using $_FILES['file'] cat an index referring the related property, however, you can only find the original file name using $_FILES['file']['name'] but not the full path. Does someone happen to know how to get the full name of the original file?
Reply to this.
Exra at 31 Aug, 2007 08:39
okay well technically if you could just open the file and return each byte as either binary, hex, or dec you could write the file to the server yourself. so you could in essance send a large string of text(or multiple) and have that write to a file on the other side.
Reply to this.
praveen at 04 Sep, 2007 12:57
Hi,
Thank you it is realy very good idea, i used it, it is woking well
thank you
Praveen
Reply to this.
Levi Putna at 04 Oct, 2007 11:53
Thanks for this example, many other examples of this method were over complicated and made it hard to understand the theory. I think you were correct in saying this is not ajax but you can combine this method with a ajax call to get updates on the upload progress.

Nice work.
Reply to this.
David Preece at 24 Oct, 2007 01:21
Hey, thanks - an excellent reference for the technique in that it strips all the extraneous crap :)

BTW - The "not Ajax" people: The _point_ of Ajax is to not have to reload the page, regardless of the technique used.
Reply to this.
Gideon at 06 Jun, 2008 09:26
Actually, AJAX stands for "Asynchronous Javascript And XML" which means that it actually requires the XML and JavaScript.. it's in the name.
Reply to this.
Anonymous at 03 Jan, 2008 10:49
Hey Thanks for this Example
Reply to this.
niki at 08 Jan, 2008 03:38
Please help me . How i upload file using ajax ? Any one knows about it.I am very sad :(. Please help
Reply to this.
Anonymous at 15 Feb, 2008 07:59
Pressing the back button on my browser (Fire Fox 2.0.0.12) also tells me a file has uploaded. Lovely stuff.
Reply to this.
Ajeet Singh at 28 Feb, 2008 02:25
Hey thanx for the code & the concept , i have read a lot about iframes in the wrox professional
& Ajax Design patterns , and i am sure that u have used that the basics quiet right , in all a simple idea but with great impact.

I am also looking for the progress bar and State Complete Callbacks after the file upload process.

Thanx Again.
Reply to this.
programmer cum philospher at 04 Mar, 2008 05:44
indeed it is not ajax.but this is the only way to upload file that can give you ajax feel.Ajax can be used to show the status.You can download ajax file upload class from php classe(it also uses ifrmae technique)
Reply to this.
DrSamba at 03 Apr, 2008 01:29
There is no cross-browser compatible way that I know of to upload files using Javascript. The reason is that for security reasons, Javascript is blocked from accessing the client's file system. The only way around that is by using signed scripts, but those work in Netscape and Mozilla only, not in IE.
Reply to this.
leo at 06 Apr, 2008 11:40
Then how the f*** does Gmail do it? :S
Reply to this.
Anonymous at 02 May, 2008 02:34
Gmail uses an iframe
Reply to this.
IT IS AJAX at 08 Apr, 2008 04:38
AJAX is asynchronous, in that extra data is requested from the server and loaded in the background without interfering with the display and behavior of the existing page. JavaScript is the scripting language in which AJAX function calls are usually made.[1] Data is retrieved using the XMLHttpRequest object that is available to scripting languages run in modern browsers, or, alternatively, through the use of Remote Scripting in browsers that do not support XMLHttpRequest. In any case, it is not required that the asynchronous content be formatted in XML.

Thanks for the script!.
Reply to this.
ngonar at 13 May, 2008 02:33
visit my website www.karyaiman.com

it is using ajax
it has no refresh and using the object XMLHTTPRequest.

this is the basic thing of ajax.

what you are using is the old version of web before Ajax method is well known.
many web programmer using iframe to reduce the refreshed page.

regrds,


ngonar
Reply to this.
siner at 04 Jul, 2008 04:21
Hello there,

I don't know what I'm doing wrong: the form gets submitted and the upload.php gets loaded, but no into the iframe, it's displayed normally as a new page.

Any suggestions?

Thanks in advance!

Regard siner
Reply to this.
Binny V A at 06 Jul, 2008 11:30
Is there any JS errors on that page?
Reply to this.
Anonymous at 08 Jul, 2008 05:28
I modified the code like this, since I build the whole form dynamically:

frm = document.createElement("iframe")
document.body.appendChild(frm)
.
.
.

doc = document.createElement("form")
document.body.appendChild(doc)
doc.enctype = doc.encoding = "multipart/form-data" // ensure it will work with IE and FF
doc.action = "_hnew"
doc.method = "post"
doc.target = "frm"
.
.
.

it works fine with FireFox, IE makes everythink ok except for the fact that it opens a new window with a blank page inside it, how can I get rid of that annoying extra window???
Reply to this.
etude at 27 Jul, 2008 10:34
ahem, you need nothing of the js-code. Just write it this way:

<form id="file_upload_form" method="post" enctype="multipart/form-data" target="upload_target" >
<iframe id="upload_target" name="upload_target" <strong> src="upload.php" style="width:0;height:0;border:0px solid #fff;"></iframe>
</form>
Reply to this.
Anonymous at 28 Jul, 2008 09:46
Why did this need javascript to point to the target?
Setting a target in the HTML works fine too :?
Reply to this.
przyciemnianie szyb at 14 Aug, 2008 04:41
nice i was looking for that type of upload script
Reply to this.
Anonymous at 23 Aug, 2008 03:42
Personally I use swfupload which is free and opensource. I think it is better and faster to integrate. swfupload.org. The problem is that it is in flash and some people don't like the idea of having flash on their site, but it already comes with progress bar and everything else. You can see an implementation that uses it on Kiqlo
Reply to this.
Anonymous at 25 Aug, 2008 04:24
When running this script in firefox with firebug, it works the file was uploaded. But if you check firebug [HTML] --> [Net] there are a post request to upload.php.
In the [POST] tag, there are nothing inside,
in the [Response] Tag, there are a error "no file specified"

the request seems execute more than one time
Reply to this.
Anonymous at 17 Sep, 2008 11:33
firebug does not cache responses, thus requiring the post to be sent again, as this is not possible with files, the post request is empty
Reply to this.
Aruna at 27 Aug, 2008 03:53
great article..
i was searching for this since long time..
Reply to this.
fuleo at 06 Sep, 2008 09:32
Been more than 1 year since this good article.

Is there really no other alternative to "Ajax file upload" without using iFrame... ?
Reply to this.
N.Arun at 12 Sep, 2008 10:14
can you give idea to display the uploaded image in the same page without reload
Reply to this.
Nitin at 22 Sep, 2008 10:09
You can't really call it an AJAX file upload. It's an IFRAME file upload. AJAX is a totally different technology.
Reply to this.
Peti at 23 Oct, 2008 12:58
Jaj hát én mikor rájöttem má erre bazmeg...
Reply to this.
Anonymous at 30 Oct, 2008 04:12
$("upload_target").onload=function() { alert("Uploaded"); }
anyone know is this will work at all in IE, this "call back" is very handy. works everywhere except IE.
Reply to this.
Binny V A at 31 Oct, 2008 11:48 Reply to this.
pmv at 03 Dec, 2008 12:14
Awesome, thanks.
Reply to this.
Anonymous at 13 Dec, 2008 07:01
This is really cool feature. Got the idea: hidden iframe, thanks for this great article
Reply to this.
Bouni at 30 Dec, 2008 11:51
Hello,

first of all THANKS :) (Hope i get this to work ;) )

I tryed everything, but it will not work ??
Im using Firefox 3.0.5
[code]
<form id='file_upload_form' method='post' enctype='multipart/form-data' action='php/misc/file_upload.php' target='upload_target'>
<input name='file' id='file' size='27' type='file' />

<input name='action' value='Upload Image' type='submit'>

<iframe id='upload_target' name='upload_target' src='php/misc/file_upload.php' style='border: 1px solid rgb(204, 204, 204); width: 400px; height: 100px;'></iframe>
</form>
[/code]
This is my Code.

When i click on Submit the whole page reloads and nothing habbens ??

Can someone help me, please.

I dont know where the promblem comes from !?


Thanks


Bouni

Please excuse my bad english ;)

Reply to this.
Sebinio at 08 Jan, 2009 11:05
Bouni,

this is what i have and works in FF 3.0.5

<form id="file_upload_form" method="post" enctype="multipart/form-data" action="upload_file.php" target="upload_target">
<input name="file" id="file" size="27" type="file" />

<input type="submit" name="action" value="Upload" />

<iframe id="upload_target" name="upload_target" src="" style="width:100px;height:100px;border:1px solid #ccc;"></iframe>
</form>
Reply to this.
Ged at 16 Feb, 2009 02:19
http://en.wikipedia.org/wiki/Ajax_(programming)

It's Ajax. Not AJAX, but Ajax. Now are the 'purists' content? :P. They should see Comet if they don't like this as Ajax. Comet's an even cruftier hack, but it does something otherwise impossible, even with Ajax. See below for Wikipedia's support.

"Ajax, or AJAX (Asynchronous JavaScript and XML), is a group of interrelated web development techniques used to create interactive web applications or rich Internet applications. With Ajax, web applications can retrieve data from the server asynchronously in the background without interfering with the display and behavior of the existing page. The use of Ajax has led to an increase in interactive animation on web pages.[1][2] Data is retrieved using the XMLHttpRequest object or through the use of Remote Scripting in browsers that do not support it. Despite the name, the use of JavaScript and XML is not actually required, nor do the requests need to be asynchronous.[3] The acronym AJAX has thus changed to the term Ajax, which does not represent these specific technologies.[4]"
Reply to this.
Anonymous at 10 Apr, 2009 02:14
This is not AJAX!
Reply to this.
Anonymous at 11 May, 2009 04:25
Before XMLHttpRequest became as native as it is today, people used iframes to retrieve data dynamically (gmail did this too).
It really doesn't matter if he uses an iframe or an XMLHttpRequest since the only difference between the two is that iframe actually renders the response and XMLHttpRequest doesn't (ofcouse you have a wider variety of settings for xmlhttprequest but for this case it does not matter).

The thing is, that even if he did this using XMLHttpRequest it wouldn't matter because the results will be the same.
Reply to this.
Joe at 16 Jun, 2009 04:21
This blog helps a lot. I studied this example and I managed to simplify it further.

Actually, you don't need to setup the init & onload function because IFRAME supports onLoad (perhaps you need it for older browser) and FORM also has target attribute which you can just point to the IFRAME.

joekuan.wordpress.com/2009/06/12/ajax-a-simplified-version-of-file-upload-form-using-iframe/

Hope this helps.
Reply to this.
ulfat at 01 Jul, 2009 09:54
Hi!

Is there a way so that we can check when response has been completed and also I want to check what is in the response.

My problem is: I post my form to slideshare api and get its response.Now this response comes into iframe and i am able to see it.but in coding i want to read this response.I have checked for innerHTML property of iframe using JavaScript but it is not working.The goal to achieve is to check the response and update text on the form so that user can see the status of uploading.
Any help.

Regards
Ulfat Hussain
Reply to this.
Comment

Please dont enter you comments in this form - this is a fake form to confuse spamming bots. The next form is the real one.




Comment




Comment Formating : HTML tags a, strong, em, b, i, code, pre, p and br allowed. Other tags will be shown as code(< will become &lt;). Urls, Line breaks will be auto-formated.