JavaScript讀取本地圖片到瀏覽器
阿新 • • 發佈:2019-01-26
程式碼:
效果:(分別為Chrome、IE)<html> <head> <script type="text/javascript"> function getFileUrl(sourceId) { var url; if (navigator.userAgent.indexOf("MSIE")>=1) { // IE url = document.getElementById(sourceId).value; } else if(navigator.userAgent.indexOf("Firefox")>0) { // Firefox url = window.URL.createObjectURL(document.getElementById(sourceId).files.item(0)); } else if(navigator.userAgent.indexOf("Chrome")>0) { // Chrome url = window.URL.createObjectURL(document.getElementById(sourceId).files.item(0)); } return url; } function preImg(sourceId, targetId) { var url = getFileUrl(sourceId); var imgPre = document.getElementById(targetId); imgPre.src = url; } </script> </head> <body> <input type="file" name="imgOne" id="imgOne1" onchange="preImg(this.id,'imgPre');" /> <img id="imgPre" src="" width="300px" height="400px" style="display: block;" /> </body> </html>