input.file上传图片| FileReader h5新特性
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>input file图片上传</title> </head> <body> <input type="file" accept="image/*" id="file" value="" /> <div id="uploadImg" style="width: 500px; height: 500px;"></div> </body> <script> var oUploadImg = document.querySelector("#uploadImg"); //获取uploaImg节点, oFile = document.querySelector("#file"); //获取input file节点 console.log(oUploadImg); console.log(oFile); console.log(oFile.files); oFile.addEventListener("change", function() { // console.log(oUploadImg); // console.log(oFile); console.log(this); //this指针指向input console.log(this.files); var file = this.files[0]; console.log(file.type); console.log(file.type.indexOf("image")); //输出0的时候成立,-1的时候不成立 if (file.type.indexOf("image") == 0) { var reader = new FileReader(); //创建FileReader对象实例reader reader.readAsDataURL(file); //将图片url转换为base64码 reader.onload = function(e) { var newUrl = this.result; console.log(newUrl); oUploadImg.style.backgroundImage = "url(" + newUrl + ")"; }; console.log(reader.result); console.log(reader); console.log(reader); } }); </script> </html>