1 <!doctype html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <meta name="viewport" 6 content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> 7 <meta http-equiv="X-UA-Compatible" content="ie=edge"> 8 <title>本地单图上传预览</title> 9 </head> 10 <style> 11 img { 12 border: 1px solid #000; 13 background-color: #ccc; 14 min-width: 60px; 15 min-height: 60px; 16 } 17 </style> 18 <body> 19 20 <input type="file" id="upImg" onchange="preImg(this.id,'imgPre');"/> 21 <img id="imgPre" src="" style="display: block;"/> 22 23 <script> 24 /** 25 * 本地图片预览 26 */ 27 // 获取上传文件地址函数 28 function getFileUrl(sourceId) { 29 var url; 30 var elUpload = document.getElementById(sourceId); 31 if (navigator.userAgent.indexOf("MSIE") >= 1) { // IE下的地址 32 url = elUpload.value; 33 } 34 else if (navigator.userAgent.indexOf("Firefox") > 0) { // Firefox下的地址 35 url = window.URL.createObjectURL(elUpload.files.item(0)); 36 } 37 else if (navigator.userAgent.indexOf("Chrome") > 0) { // Chrome下的地址 38 url = window.URL.createObjectURL(elUpload.files.item(0)); 39 } 40 console.log(url); 41 return url; 42 } 43 44 function preImg(sourceId, targetId) { 45 var imgPre = document.getElementById(targetId); 46 imgPre.src = getFileUrl(sourceId);// 获取地址 47 } 48 </script> 49 </body> 50 </html>
留下你的足迹求推荐呦