js 上傳圖片預覽
阿新 • • 發佈:2018-11-28
<head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> </head> <body> <div id="localImag"> <img id="preview" style="display:block; border:1px solid red; width: 150px; height: 180px;"> </div> <input id="doc" type="file" name="file" onchange="javascript:setImagePreview();"> <script type="text/javascript"> //下面用於圖片上傳預覽功能 function setImagePreview(avalue) { var docObj=document.getElementById("doc"); var imgObjPreview=document.getElementById("preview"); if(docObj.files &&docObj.files[0]){ imgObjPreview.src = window.URL.createObjectURL(docObj.files[0]); }else{ //IE低版本下,使用濾鏡 docObj.select(); var imgSrc = document.selection.createRange().text; var localImagId = document.getElementById("localImag"); //必須設定初始大小 localImagId.style.width = "150px"; localImagId.style.height = "180px"; //圖片異常的捕捉,防止使用者修改後綴來偽造圖片 try{ localImagId.style.filter="progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale)"; localImagId.filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src = imgSrc; }catch(e){ alert("您上傳的圖片格式不正確,請重新選擇!"); return false; } imgObjPreview.style.display = 'none'; document.selection.empty(); } } </script> </body>