Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
127
rated 0 times [  130] [ 3]  / answers: 1 / hits: 60960  / 14 Years ago, thu, november 4, 2010, 12:00:00

I want to preview an image before uploading it to the server. I have written a little bit code for it, but it is only being previewed in Internet Explorer, not in other browsers like Safari, Chrome, Firefox, due to some type of security reasons. Is there any solution to preview the image in these browsers?



    <body>
<form name=Upload enctype=multipart/form-data method=post>
Filename: <INPUT type=file id=submit>
<INPUT type=button id=send value=Upload>
</form>
<div
id=div
align=center
style=height: 200px;width: 500px;border-style: ridge;border-color: red>
</div>
</body>

<script type=text/javascript>
var img_id=0
var image = new Array()
document.getElementById('send').onclick=function()
{
img_id++
var id=imgid+img_id
image = document.getElementById('submit').value;
document.getElementById('div').innerHTML=<img id='+id+' src='+image+' width=500px height=200px>
}
</script>
</html>

More From » javascript

 Answers
135

For Firefox. Because of security it has a truncated path. However, they have provided other ways of doing this:



var img = document.createElement(IMG);
if(document.all)
img.src = document.getElementById('submit').value;
else
// Your solution for Firefox.
img.src = document.getElementById('submit').files.item(0).getAsDataURL();
document.getElementById('div').appendChild(img);


The below is working in Internet Explorer 7 and Firefox 3.



<style type=text/css>
#prevImage {
border: 8px solid #ccc;
width: 300px;
height: 200px;
}
</style>
<script type=text/javascript>
function setImage(file) {
if(document.all)
document.getElementById('prevImage').src = file.value;
else
document.getElementById('prevImage').src = file.files.item(0).getAsDataURL();
if(document.getElementById('prevImage').src.length > 0)
document.getElementById('prevImage').style.display = 'block';
}
</script>
<pre>
IE8 needs a security settings change: internet settings, security, custom level :

[] Include local directory path when uploading files to a server
( ) Disable
(o) Enable
</pre>
<form>
<input type=file name=myImage onchange=setImage(this); />
</form>
<img id=prevImage style=display:none; />


Documentation of File List object on MDC


[#95082] Tuesday, November 2, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kamronr

Total Points: 749
Total Questions: 110
Total Answers: 122

Location: Dominica
Member since Sat, Nov 5, 2022
2 Years ago
kamronr questions
Mon, Dec 21, 20, 00:00, 3 Years ago
Fri, Oct 16, 20, 00:00, 4 Years ago
Sat, Oct 3, 20, 00:00, 4 Years ago
Sun, Jul 28, 19, 00:00, 5 Years ago
;