HTML代碼部分: 思路:下面代碼中我利用css的z-index屬性將input="file”標簽隱藏在了id=btnSelect元素下面,通過觸發a標簽的點擊后,彈出文件選擇框。下面的masklayer用於點擊確認按鈕后的彈出層,避免用戶重復點擊確認按鈕。 復制代碼 代碼如下: <div id="wp" class="warpper"> <a id="btnSelect">單擊選擇要上傳的照片</a> <input id="uploadFile" type="file" name="myPhoto" /> <button id="btnConfirm" class="btn" >確認上傳</button> </div> <div id="maskLayer" class="mask-layer" style="display:none;"> <p>圖片正在上傳中...</p> </div> JS圖片文件驗證部分: 驗證部分為:大小,是否已經選擇,文件的類型 三個部分。第一個createObject方法為創建本地圖片文件的預覽路徑,依次驗證是否為空,文件類型以及文件大小,不滿足條件則一律返回 false,滿足以上3個條件后,在dom中生成圖片預覽,添加img元素,然后利用createObjectURL()方法獲取預覽路徑。 代碼: 復制代碼 代碼如下: //獲取數據的URL地址 function createObjectURL(blob) { if (window.URL) { return window.URL.createObjectURL(blob); } else if (window.webkitURL) { return window.webkitURL.createObjectURL(blob); } else { return null; } } //文件檢測 function checkFile() { //獲取文件 var file = $$("uploadFile").files[0]; //文件為空判斷 if (file === null || file === undefined) { alert("請選擇您要上傳的文件!"); $$("btnSelect").innerHTML = "單擊選擇要上傳的照片"; return false; } //檢測文件類型 if(file.type.indexOf('image') === -1) { alert("請選擇圖片文件!"); return false; } //計算文件大小 var size = Math.floor(file.size/1024); if (size > 5000) { alert("上傳文件不得超過5M!"); return false; }; //添加預覽圖片 $$("btnSelect").innerHTML = "<img class=\"photo\" src=\""+createObjectURL(file)+"\"/>"; };
轉自:http://www.jb51.net/html5/171339.html