FileReader - Web API 接口 | MDN
DEMOjavascript
使用FileReader對象,web應用程序能夠異步的讀取存儲在用戶計算機上的文件(或者原始數據緩衝)內容,可使用File對象或者Blob對象來指定所要處理的文件或數據.其中File對象能夠是來自用戶在一個<input type="text" />元素上選擇文件後返回的FileList對象,也能夠來自拖放操做生成的 DataTransfer對象,還能夠是來自在一個HTMLCanvasElement上執行mozGetAsFile()方法後的返回結果.html
1 <!Doctype html> 2 <html> 3 <head> 4 <title>上傳圖片顯示預覽圖</title> 5 <style> 6 #result img{ 7 height:100px; 8 display:inline-block; 9 margin-right:10px; 10 margin-bottom:10px; 11 } 12 </style> 13 </head> 14 <body> 15 <div class="add_imgs"> 16 <p> 17 <label>請選擇一個圖像文件:</label> 18 <input type="file" id="file_input" style="display:none;" /> 19 </p> 20 <div id="result"> 21 <a href="javascript:void(0);" class="add_img_btn">添加圖片</a> 22 </div> 23 </div> 24 <div class="add_imgs"> 25 <p> 26 <label>請選擇一個圖像文件:</label> 27 <input type="file" id="file_input" style="display:none;" /> 28 </p> 29 <div id="result"> 30 <a href="javascript:void(0);" class="add_img_btn">添加圖片</a> 31 </div> 32 </div> 33 <script src="jquery-2.2.1.min.js"></script> 34 <script> 35 $(".add_img_btn").unbind("click").on("click",function(){ 36 $(this).parents(".add_imgs").find("input[type=file]").click(); 37 var result = $(this).parent(); 38 var input = $(this).parents(".add_imgs").find("input[type=file]"); 39 dads(result,input); 40 }) 41 42 43 function dads(result,input){ 44 if(typeof FileReader==='undefined'){ 45 result.innerHTML = "抱歉,你的瀏覽器不支持 FileReader"; 46 input.setAttribute('disabled','disabled'); 47 }else{ 48 $(input).unbind("change").on("change",function(){ 49 var file = this.files[0]; 50 if(!/image\/\w+/.test(file.type)){ 51 alert("文件必須爲圖片!"); 52 return false; 53 } 54 var reader = new FileReader(); 55 reader.readAsDataURL(file); 56 reader.onload = function(e){ 57 $(result).append('<img src="'+this.result+'" alt="" />'); 58 } 59 }) 60 } 61 } 62 </script> 63 </body> 64 </html>