954,566 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

javascript image preview

hello all. i've bee learning php for the last couple of weeks while designing a site but i am now frequently running into situations where i need to use javascript. i have a page where i want a user to browse for a pic with a file field and i would like the image to be displated as a preview before the user uploads the pic. i found this script...

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 +"'");
document.all.imagepreview.style.visibility ='visible';
}

...but it dosent seem to be working for me, i'm using IE7 by the way. any help would be appreciated. thanks in advance!

slrobinson1983
Newbie Poster
15 posts since Feb 2011
Reputation Points: 10
Solved Threads: 0
 

Firstly the Code in eval() isn't correct:

eval('document.documentGetElementById("imagepreview").innerHTML= content;');

Secondly if this is pure JavaScript, it will not work, because many browsers do not allow Javascript to access local resources. Error:

Not allowed to load local resource: file:///C:/fakepath/DSC00053.JPG
Agarsia
Junior Poster
114 posts since Feb 2011
Reputation Points: 10
Solved Threads: 25
 

i found this script and it seems to be working fine for me. can anybody tell me how to alter this so that it dosent alter the dimensions of the image. id like to have it previewed in its original size. thanks for the help all.

slrobinson1983
Newbie Poster
15 posts since Feb 2011
Reputation Points: 10
Solved Threads: 0
 
<script type="text/javascript">
var fileTypes=["bmp","gif","png","jpg","jpeg"];
var outImage="previewField";
var defaultPic="spacer.gif";

function preview(what){
var source=what.value;
var ext=source.substring(source.lastIndexOf(".")+1,source.length).toLowerCase();
for (var i=0; i<fileTypes.length; i++) if (fileTypes[i]==ext) break;
globalPic=new Image();
if (i<fileTypes.length) globalPic.src=source;
else {
globalPic.src=defaultPic;
alert("THAT IS NOT A VALID IMAGE\nPlease load an image with an extention of one of the following:\n\n"+fileTypes.join(", "));
}
setTimeout("applyChanges()",200);
}
var globalPic;

function applyChanges(){
var field=document.getElementById(outImage);

field.src=globalPic.src;
}
</script>


this should work

Agarsia
Junior Poster
114 posts since Feb 2011
Reputation Points: 10
Solved Threads: 25
 

thanks agarsia that worked great

slrobinson1983
Newbie Poster
15 posts since Feb 2011
Reputation Points: 10
Solved Threads: 0
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: