我想在将图像上传到服务器之前预览图像.我已经为它编写了一些代码,但由于某些安全原因,它只是在Internet Explorer中预览,而不是在Safari,Chrome,Firefox等其他浏览器中预览.有没有解决方案在这些浏览器中预览图像?
<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>
解决方法
对于Firefox.由于安全性,它有一个截断的路径.但是,他们提供了其他方法:
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);
以下是在Internet Explorer 7和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;" />