网上搜的资料一大堆,但很多都是不完整或者不能用的,自己做了一个简单的版本。
html:
<input type="file" id="to-upload"> <div><img src="" alt="" id="myimg"><span id="img-msg"></span></div>
js:
var oUpload = document.getElementById('to-upload'); var oImg = document.getElementById('myimg'); var oMsg = document.getElementById('img-msg'); oUpload.onchange = function () { var file = this.files[0]; var oFile = new FileReader(); //将文件转成某种能识别的URL地址 oFile.readAsDataURL(file); oFile.onload = function (ev) { oImg.src = ev.target.result; oMsg.innerHTML = (ev.total / 1024).toFixed(2) + 'KB'; } };
完整代码:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <input type="file" id="to-upload"> <div><img src="" alt="" id="myimg"><span id="img-msg"></span></div> <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script> <script> var oUpload = document.getElementById('to-upload'); var oImg = document.getElementById('myimg'); var oMsg = document.getElementById('img-msg'); oUpload.onchange = function () { var file = this.files[0]; var oFile = new FileReader(); //将文件转成某种能识别的URL地址 oFile.readAsDataURL(file); oFile.onload = function (ev) { oImg.src = ev.target.result; oMsg.innerHTML = (ev.total / 1024).toFixed(2) + 'KB'; } }; </script> </body> </html>
参考:
http://www.cnblogs.com/liaojh/p/5209433.html
http://www.cnblogs.com/tugenhua0707/p/3568134.html