Wednesday, February 23, 2011

Image upload without page refresh

If you are uploading a file without refreshing a page, you do not need any ajax or any flash uploader for such a realtime uploader. This can be easily achieved by simple conventional HTML and javascript. The solution is too simple to believe it exist. The idea is to use a iframe and redirect the upload destination page to the iframe instead of the current page.

This is achieved by the "target" attribute. You can use this attribute to plain hyperlinks as well. For example if you have <a href="mypage.html" target="iframe_1">Click</a> and you have a iframe whose id is "iframe_1", then the page mypage.html will open in the iframe instead of the current page. So the same concept applies for file upload without refreshing current page.

You need to have 2 php files, let the first file be, "upload.php" with the following:

 <head><title>Image upload without page refresh</title>
 <script type="text/javascript">
 function upload_started(){
 function upload_completed(){
  <form method="post" action="upload_target.php" enctype="multipart/form-data" target="hidden_upload" onsubmit="upload_started()">
   <div style="float:left;margin-right:10px">Select a file:</div>
   <input type="file" name="uploader" style="float:left;margin-right:10px">
   <input type="submit" value="Upload"  style="float:left;margin-right:10px">
   <img src="loading.gif" id="upload_status" style="display:none;float:left;margin-right:10px">
  <iframe id="hidden_upload" name="hidden_upload" style="display:none" ></iframe>

Create another file, "upload_target.php" with the following:

echo '<pre>';
echo '</pre>';

Also download a loading.gif(animated gif e.g. ajax loading type) and save in the same directory.

Execute upload.php and upload a file. The file will be posted and the page will not be refreshed also. If you want to see what is happening then make a change in upload.php as follows:

<iframe id="hidden_upload" name="hidden_upload" style="display:none" ></iframe>
<iframe id="hidden_upload" name="hidden_upload" style="display:block" ></iframe>



  1. great post helped me a lot................

  2. Well, where do you tell it to upload the file to a folder?
    I don't see any code for moving the tmp file to a folder?

    Where does the file upload to???

    1. This article is not about how to upload a file. Please find some basic level PHP upload tutorial before using the above. After you know how to upload a file in PHP, use that script in "upload_target.php".

      But again, unless you know, how to upload a file in PHP, the above is not of any help to you.

  3. Thank you very much!!! You did helped me for lot of support!!!

  4. Hola! Just the one i've been searching for.. this one works for me, thank you dude!

  5. Hi! The greatest and easiest way to upload files!!! Thanks!! From Russia with love