1. 程式人生 > >頁面圖片上傳前,讓圖片在頁面顯示

頁面圖片上傳前,讓圖片在頁面顯示

記錄是為了更好的成長!

 1、程式碼示例(顯示並判斷圖片大小和格式)

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title></title>
        <script src="js/jquery-3.3.1.js"></script>
    </head>
    <body>
        <img id="imghead"  width
="260" height="180" /> <!--圖片顯示位置--> <input type="file" name="file" id="file" onchange="getPhotoSize(this)" /> <script> // 選擇圖片顯示 function imgChange() { //獲取點選的文字框 var file =document.getElementById("file");
var imgUrl =window.URL.createObjectURL(file.files[0]); var img =document.getElementById('imghead'); img.setAttribute('src',imgUrl); // 修改img標籤src屬性值 }; function lookImg() { $("#img_a").remove(); $("#show
").show(); var r= new FileReader(); f=document.getElementById('file').files[0]; r.readAsDataURL(f); r.onload=function (e) { document.getElementById('show').src=this.result; }; } //判斷照片大小 function getPhotoSize(obj){ //檔案type var photoExt = obj.value.substr(obj.value.lastIndexOf(".")).toLowerCase(); if(!(photoExt=='.jpg'||photoExt=='.png'||photoExt=='.jpeg'||photoExt=='.gif')){ alert("檔案格式不符合要求!"); document.getElementById('file').value=''; return false; } var fileSize = 0; var isIE = /msie/i.test(navigator.userAgent) && !window.opera; if (isIE && !obj.files) { var filePath = obj.value; var fileSystem = new ActiveXObject("Scripting.FileSystemObject"); var file = fileSystem.GetFile (filePath); fileSize = file.Size; } else{ fileSize = obj.files[0].size; } //檔案大小 fileSize=Math.round(fileSize/1024*100)/100; if(fileSize>=200){ alert("圖片過大,超過200k,請選擇較小的圖片"); document.getElementById('file').value=''; return false; } imgChange(); } </script> </body> </html>

 

 

 

以上內容代表個人觀點,僅供參考,不喜勿噴。。。