JavaScript to Preview a Local Image Before Uploading

My friend Santhosh asked this question. He has an image upload form in a webpage. User selects an image to upload from the local computer by clicking the browse button. Now, he would like to preview the image from the local computer. Good question.

I liked the question mainly because I had the same question 4 years ago, for an intranet project (IE only). I wrote the script myself (a change from the usual practice of copying from somewhere!). Now all I have to do is to share it with him. Then why not share it with anybody looking for this by posting in the blog? That sounds good to me. So here it goes.


This CSS ID goes to the <head> or CSS include file

.imagepreview { position: relative; visibility: visible; width: 150; height: 150; clip: rect(0,300,300,0);}

Define an ID in the HTML page in an appropriate location to display the preview image

<div id=”imagepreview><img src=”no-preview-image-name” /></div>

In the form file element, add the onchange event

<input type=”file” onchange=”showLocalImage(this.value)” />

This function goes in the <head> tag or in a JavaScript include file.

function showLocalImage(imgname) {
imgname = imgname.replace(/\\/g,”/”);
imgname = imgname.replace(/\’/g,”\\'”);
content = “<img src=\”” + String(imgname) + “\” border=\”0\” height=\”150\” weight=\”150\”>”;
eval(‘document.all(“imagepreview”).innerHTML=\” + content +”‘”); =’visible’;

Disclaimer: I did not test this script in all browsers. You may use this idea, but do not trust the code to work for you! 🙂

Be the first to comment

Leave a Reply