Home > Web Front-end > H5 Tutorial > H5 implements functional code for uploading local images and previewing them

H5 implements functional code for uploading local images and previewing them

不言
Release: 2018-06-11 15:39:06
Original
4127 people have browsed it

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>
Copy after login

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 === &#39;undefined&#39;) { 
  alert("浏览器版本过低,请先更新您的浏览器~"); 
  input.setAttribute(&#39;disabled&#39;, &#39;disabled&#39;); 
 } else { 
  input.addEventListener(&#39;change&#39;, 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 = $(&#39;<p class="figure"><p class="figure-hd">我的头部</p><p class="figure-bd"><img src="&#39; + this.result + &#39;" /><textarea placeholder="请输入文字"></textarea></p></p>&#39;); 
  figure.appendTo(figureBox); 
  } 
 } 
 } 
}
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template