This article mainly introduces in detail the implementation code of H5 uploading local images and previewing them. It has certain reference value. Interested friends can refer to it
Recent work requires H5 upload display The function of the picture, as shown in the figure:
Directly upload the code:
html part
<p class="works-wrap"> <p class="figure-box" id="figure_box"></p> <p class="add-btn"> <input type="file" id="imgUploadBtn" /> <a href="javascript:void(0);" rel="external nofollow" ><i></i>添加作品</a></p> </p> </p>
I used css to set input[type=file] to optical:0; so that it looks more like a native upload.
var addWork = { add: function(btn, figure_box) { var figureBox = document.getElementById(figure_box); //获取显示图片的p元素 var input = document.getElementById(btn); //获取选择图片的input元素 //这边是判断本浏览器是否支持这个API。 if (typeof FileReader === 'undefined') { alert("浏览器版本过低,请先更新您的浏览器~"); input.setAttribute('disabled', 'disabled'); } else { input.addEventListener('change', readFile, false); //如果支持就监听改变事件,一旦改变了就运行readFile函数。 } function readFile() { var file = this.files[0]; //获取file对象 //判断file的类型是不是图片类型。 if (!/image\/\w+/.test(file.type)) { alert("请上传一张图片~"); return false; } var reader = new FileReader(); //声明一个FileReader实例 reader.readAsDataURL(file); //调用readAsDataURL方法来读取选中的图像文件 //最后在onload事件中,获取到成功读取的文件内容,并以插入一个img节点的方式显示选中的图片 reader.onload = function(e) { // 创建一个新增的图片和文字input var figure = $('<p class="figure"><p class="figure-hd">我的头部</p><p class="figure-bd"><img src="' + this.result + '" /><textarea placeholder="请输入文字"></textarea></p></p>'); figure.appendTo(figureBox); } } } }
The above is the entire content of this article. I hope it will be helpful to everyone’s study. For more related content, please pay attention to the PHP Chinese website!
Related recommendations:
Use 63 lines of HTML5 code to implement the Snake game
HTML5 to implement messages and replies page
The above is the detailed content of H5 implements functional code for uploading local images and previewing them. For more information, please follow other related articles on the PHP Chinese website!