檔案二進位制上傳圖片
阿新 • • 發佈:2019-01-25
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <style> label{ height:40px; width:100px; border:1px solid #666; display:block; text-align:center; line-height:40px; border-radius:10px; background:lightgreen; opacity: 1; } input{ display:none; } span{ display:block; height:100%; width:100%; } #canvas { border:1px solid #666; } </style> <script src="http://libs.baidu.com/jquery/1.8.3/jquery.min.js"></script> </head> <body> <label> <input type="file" id="file" /> <span>上傳檔案</span> </label> <canvas width="300" height="300" id="canvas"></canvas> </body> <script> $("#file").change(function (){ var file = new FileReader();//讀取檔案2進位制 file.onload = function(e){ var base64 = e.target.result; var img = new Image();//建立一個圖片物件 img.onload = function (){ var canvas = $("#canvas").get(0); var ctx = canvas.getContext("2d"); //使用drawImage顯示圖片 ctx.drawImage(img,0,0,canvas.width,canvas.height); } //把base64新增到圖片上 img.src = base64; }; file.readAsDataURL(this.files[0]); }); </script> </html>