<div class="btn-box"><button class="btnImg">上传图片</button><input id="file" type="file" name="pictureFile" class="file-ipt"><img class="img" id="showimg" width="200px" height="200px" src="" style="display: none"/></div>
js:
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.0.js"></script><script type="text/javascript">var showimg = document.getElementById(‘showimg‘);var fileBtn = document.getElementById(‘file‘);$(‘.btnImg‘).on(‘click‘,function(){$(‘#file‘).click() //点击按钮触发input})// 获取上传文件信息fileBtn.onchange = function () {var file = this.files[0];if(window.FileReader) {var fr = new FileReader();fr.readAsDataURL(file);fr.onload = function(e) {console.log(e.target); // e.target返回FileReader对象,里面包含:事件,状态,属性,结果等console.log(this); // 同e.target返回结果一样,两者等价console.log(e.target.result); // 读取的结果,dataURL格式的showimg.style.display="inline"showimg.src = this.result; // 图片可显示出来};} else {alert(‘暂不支持FileReader‘);};};</script>
.img {width: 200px;height: 200px;border: 1px solid rgb(143, 59, 59);border-radius: 5px;}.file-ipt {height: 0;}.btnImg {width: 100px;height: 30px;background-color: skyblue;color: white;margin-right: 80px;border: none;border-radius: 10px;margin-bottom: 10px;}
原文:https://www.cnblogs.com/guomouren/p/14958184.html