我想先预览图像,然后再将其上传到服务器。我已经为其编写了一些代码,但是由于某种安全原因,它只能在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;" />