Upload image using hidden iFrame (Simple Photo Manager)

Image Upload Using iFrame

Image Upload Using iFrame

You can view the working demo here.

You can download the source code here.

In this example we are using a hidden IFrame for uploading file without refreshing page.

Include IFRAME in your page.

<div id="iframe_container">
        <iframe src="pm-upload.php" frameborder="0" style="height:75px;"></iframe>
</div>

The pm-upload.php has a FROM with file input field. When user select a file for upload we have called a upload() function on onChange event of file element.

<form name="iform" action="" method="post" enctype="multipart/form-data">
    <input id="file" type="file" name="image" onChange="window.parent.upload(this);" /><br>
    <span style="font-size:11px; color:#666666;">only gif, png, jpg files.</span>
    <input type="hidden" value="" name="div_id" />
</form>

If file successfully upload and satisfy all validation conditions then we call setUploadedImage() function to setup the information of recently uploaded file on parent window. we can access the parent window javascript functions like this:

window.parent.setUploadedImage();

If there is some validation error then we call uploadError() function of parent window.

Here is complete javascript code for this tutorial:

//Call at the time of upload
function upload(fileObj){
	var par = window.document;
	var frm = fileObj.form;
	var div_id = parseInt(Math.random() * 100000);
 
	// hide old iframe
	var iframes = par.getElementsByTagName('iframe');
	var iframe = iframes[iframes.length - 1];
	iframe.className = 'hidden';
 
	// create new iframe
	var new_iframe = par.createElement('iframe');
	new_iframe.src = 'pm-upload.php';
	new_iframe.frameBorder = '0';
	new_iframe.style.height = '75px';
	par.getElementById('iframe_container').appendChild(new_iframe);
 
	// add image progress
	var images = par.getElementById('images_container');
	var new_div = par.createElement('div');
	new_div.id = div_id;
 
	var new_img = par.createElement('img');
	new_img.src = 'images/indicator2.gif';
	new_img.style.marginLeft = '33px';
	new_img.style.marginTop = '50px';
	new_div.appendChild(new_img);
	images.appendChild(new_div);
 
	var errorDiv = par.getElementById('error');
	errorDiv.innerHTML = "";
	errorDiv.style.display = 'none';
 
	// send
	frm.div_id.value = div_id;
	setTimeout(frm.submit(),5000);
}
 
//Call when upload completed
function setUploadedImage(imgSrc, fileTempName, divId) {
	var par = window.document;
 
	var images = par.getElementById('images_container');
 
	var imgdiv = par.getElementById(divId);
	var image = imgdiv.getElementsByTagName('img')[0];
	imgdiv.removeChild(image);
 
	var image_new = par.createElement('img');
	image_new.src = imgSrc;
	image_new.className = 'pic';
 
	var image_label = par.createElement('input');
	image_label.type = "text";
	image_label.maxLength = "40";
	image_label.size = "12";
	image_label.value = "Label";
	image_label.name = "title[]";
 
	var image_hidden = par.createElement('input');
	image_hidden.type = "hidden";
	image_hidden.value = "1";
	image_hidden.name = "delFlag[]";
 
	var image_name = par.createElement('input');
	image_name.type = "hidden";
	image_name.value = fileTempName + ",new";
	image_name.name = "imageName[]";
 
	var image_del_link = par.createElement('a');
	image_del_link.href = "javascript:void(0)";
	image_del_link.appendChild(par.createTextNode("Delete"));
 
	var br = par.createElement('br');
 
	imgdiv.appendChild(image_new);
	imgdiv.appendChild(image_label);
	imgdiv.appendChild(image_hidden);
	imgdiv.appendChild(image_name);
	imgdiv.appendChild(br);
	imgdiv.appendChild(image_del_link);
 
	image_label.onfocus = function() {
		eval(labelOnFocus(image_label));
	}
 
	image_label.onblur = function() {
		eval(labelOnBlur(image_label));
	}
 
	image_del_link.onclick = function() {
		eval(deleteLinkOnClick(image_del_link, ''));
	}
}
 
// call when error occurred at the time of upload
function uploadError(divId, oName) {
	var par = window.document;
	var images = par.getElementById('images_container');
	var imgdiv = par.getElementById(divId);
	images.removeChild(imgdiv);
	var errorDiv = par.getElementById('error');
	errorDiv.innerHTML = oName + " has invalid file type.";
	errorDiv.style.display = '';
}
 
function labelOnFocus(image_label) {
	if (image_label.value == "Label") {
		image_label.value = "";
	}
}
 
function labelOnBlur(image_label) {
	if (image_label.value == "") {
		image_label.value = "Label";
	}
}
 
function deleteLinkOnClick(delLink, delFlag) {
	var par = window.document;
	var imgDiv = delLink.parentNode;
	var image_hidden = delFlag == '' ? imgDiv.childNodes[2] : par.getElementById(delFlag);
 
	if (image_hidden.value == '1') {
		image_hidden.value = '0';
		delLink.removeChild(delLink.childNodes[0]);
		delLink.appendChild(par.createTextNode("Restore"));
		delLink.style.color = '#FF0000';
	}
	else {
		image_hidden.value = '1';
		delLink.removeChild(delLink.childNodes[0]);
		delLink.appendChild(par.createTextNode("Delete"));
		delLink.style.color = '#64B004';
	}
}

You can check the live demo of this tutorial and you can also download the source code of the sample demo. The demo example is very simple and only for learning purpose. You can easily extent the sample code as per your requirement.

, , ,


  1. #1 by Donovan - May 27th, 2009 at 02:06

    Wow.

    This thing is a great example of a simple, yet reasonably featured image manager. It’s wired up a little ‘like a christmas tree’. The non-dependance on external libraries will really help beginners with understanding what’s going on.

    Might I suggest revisiting this puppy with a jQueryed version? Mid level developers everywhere will love you for it.

  2. #2 by deep - June 19th, 2009 at 12:14

    hi, i really enjoy your code here. but when i try to run it myself, i get the following error message.
    Warning: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource in C:\www\photo-manager.php on line 45

    also which page are you referring to when you say Property Page?

  3. #3 by admin - June 19th, 2009 at 13:25

    @ deep
    Hi Deep,

    Have you created “images” table in your database. This example is using a table “images” for storing images details. You can find the structure of this table in “tables.sql” file.

    Other case may be you have not configured the database settings in “config.php” file. You need to give the DB name, username, password and hostname in this file.

    “Property Page” is just a static message for user. Suppose we are using this example in some Real state website. So, user can managing his/her property images from his account. So, the the images will come in the same display order as they are coming here.

  4. #4 by Stefan - October 11th, 2009 at 23:33

    Hi guys…

    I am playing around with this script and really think this is the way I want to go when doing image upload script!!!

    I would like it if you can give me advise how, in this code, I can re-size the images that is uploaded?

    THANKS FOR A GREAT SCRIPT AND TUTORIAL!!!

  5. #5 by Stefan - October 11th, 2009 at 23:36

    While we at it? How can I limit the amount of images uploaded?

    Thanks

    Stefan : Hi guys…
    I am playing around with this script and really think this is the way I want to go when doing image upload script!!!
    I would like it if you can give me advise how, in this code, I can re-size the images that is uploaded?
    THANKS FOR A GREAT SCRIPT AND TUTORIAL!!!

  6. #6 by fawzi - November 6th, 2009 at 12:21

    HI there,

    i am trying to use your method above since it looked simple and elegant.

    i did run into few problems though:
    1- I fixed the creation of the image table
    2- i entered the correct values in the config file.
    3- i gave the complete path to the photo-manager.php in the initial iframe.

    however, i am now getting an error on finding window.parent.upload.

    i added a tag to the file in your php generated htm but it still cannot find it.

    i am sure the JS is linked correctly, but it still complain about upload() is not defined.

  7. #7 by fawzi - November 6th, 2009 at 23:33

    i just read my last comment/request. i think it may be a bit ambiguous. so just to clarify, the window.parent.upload is not recognized/ not found by drupal.

    i currently put the js/pm.js file as a link within the html inside the iframe. but it is still not found.

    where should the pm.js reside for it to work??

  8. #8 by fawzi - November 7th, 2009 at 11:58

    guys, please throw me a boney…

  9. #9 by admin - November 7th, 2009 at 17:57

    @fawzi
    Hi Fawzi,

    Reading your comment I can only guess that your pm.js file path is not correct and that’s why browser not found this window.parent.upload function.
    You can check your JS file path. You can try the exact path (http://localhost/js/pm.js) instead of relative path or try ‘/js/pm.js’.
    Let me know if this resolve your problem.

  10. #10 by Tavus - June 13th, 2010 at 11:33

    hello, i run your Demo and its wonderful, but as i run your code the progress icon keeps rotating endlessly and nothing happens. it shows an error and when i click on error it says ‘null’ null is null or not an object. database is created correctly and also for a test if i copy an image manually in the folder photo i can see the image on refreshing the page.appreciating your help and thanks for your wonderfull script.

(will not be published)


Submit Comment
Subscribe to comments feed
  1. No trackbacks yet.