window.onload = function () { var input = document.getElementById("img"); if (typeof (FileReader) === 'undefined') { result.innerHTML = "抱歉,你的浏览器不支持 FileReader,请使用现代浏览器操作!"; input.setAttribute('disabled', 'disabled'); } else { input.addEventListener('change', readFile, false); } } function readFile() { var file = this.files[0]; //判断是否是图片类型 if (!/image/w+/.test(file.type)) { alert("只能选择图片"); return false; } var reader = new FileReader(); reader.readAsDataURL(file); reader.onload = function (e) { document.getElementById("data").innerText=this.result.substring(this.result.indexOf(',')+1); } }
是从别的地方拷贝过来的,这个代码大概是:
在加载后,将图片对象存到input中,先通过类型判断是否支持filereader,支持给该input加change的事件,
如果有文件载入,会调用readFile方法,先判断是否是图片类型,否返回false,
是则载入文件流读取忘记拿,并且在加载完毕后调用方法,读取子子字符串(有效段吧)
给窗口中已经存在的一个隐藏标签赋值即可。