无意中看到html5的FileRader这个对象,之前没见过,查阅了下资料发现是个读取文件的东西。于是简单实现了下将图片转换成编码:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <input id="file" type="file"></input> <div id="result"></div> <script> var file = document.getElementById('file'), result = document.getElementById('result'); file.onchange = function(){ if(!this.files.length) return; var files = Array.prototype.slice.call(this.files); if(files.length >= 9){ alert('最多只能上传9张图片'); return; } files.forEach(function(file,i){ if(!/(jpeg|png|gif|icon)$/i.test(file.type)) return; var reader = new FileReader(); reader.readAsDataURL(file);//将文件读取为DataURL reader.onload = function(){ var r = this.result; result.innerHTML = r; var img = document.createElement('img'); img.src = r; img.width = 200; img.height = 120; document.body.appendChild(img); } }); } </script> </body> </html>