码迷,mamicode.com
首页 > 移动开发 > 详细

移动端h5实现拍照上传图片并预览

时间:2017-06-21 20:04:47      阅读:3649      评论:0      收藏:0      [点我收藏+]

标签:cap   sky   基本   append   转换   upload   ash   length   ext   

.移动端实现图片上传并预览,用到h5的input的file属性及filereader对象;经测除了android上不支持多图片上传,其他基本ok实用;

一:先说一下单张图片上传(先上代码):

html结构(含多张图片容器div):

1 <div class="fileBtn"> 
2         <p>点击添加图片</p>
3         <input id="fileBtn" type="file" onchange="upload();" accept="image/*" capture="camera" multiple="multiple"/> 
4         <!--单张图片容器-->
5         <img src="" id="img"/>
6     </div>
7     <!--多张图片容器-->
8    <div class="img-box"> 
9    </div> 

 

css样式(由于默认file样式实在不好看,自定义透明覆盖改变了样式ps含多张图片容器div):

1 <style type="text/css">
2         #fileBtn{width: 100px;height: 100px; position: absolute;display: block;top: 0;left: 0;opacity: 0;} 
3         .fileBtn{width: 100px;height: 100px;border: 2px dashed lightskyblue;text-align: center;position: relative;left: 50px;top: 50px;}
4         .fileBtn p{line-height: 60px;}
5         #img{width: 100px;height: 100px;position: absolute;top: 0;left: 0;z-index: 10;display: none;}
6         .img{width: 100px;height: 100px;}
7         .img-box{margin-top: 80px;}
8     </style>

js代码:

 1 //单张图片上传
 2     function upload(){ 
 3     var $c = document.querySelector("#fileBtn");//上传出发按钮
 4     var $d = document.querySelector("#img");//图片容器
 5     var file = $c.files[0];//获取file对象单张
 6     var reader = new FileReader();//创建filereader对象
 7         reader.readAsDataURL(file);//转换数据
 8         reader.onload = function(e){//加载ok时触发的事件
 9             console.log(file);
10         $d.setAttribute("src", e.target.result);//给图片地址,显示缩略图
11         $d.style.display="block";//样式显示
12     };
13 };  

 效果图(pc端截图,没截移动端的,参考下就好;移动端也是ok的):

技术分享技术分享

 

二:多张图片上传(android不支持):

只需将在方法里改变将file全部获取并遍历;(这里还可限制上传数量就没写了;)

 1  //多张图片
 2      function uploadm(){ 
 3     var $c = document.querySelector("#fileBtn");//上传出发按钮
 4     var $d = document.querySelector(".img-box");//图片容器
 5     var file = $c.files; //获取file对象,并进行遍历
 6     console.log(file.length);
 7     for(var i=0;i<file.length;i++){
 8         var reader = new FileReader();
 9         reader.readAsDataURL(file[i]); 
10         reader.onload = function(e){ 
11         var oImg=new Image();
12         oImg.setAttribute("src", e.target.result);
13         oImg.setAttribute("class",‘img‘);
14         $d.appendChild(oImg);
15         };
16     } 
17 };  

然后注意把input的multiple属性加上;

更多方法属性可参考:http://www.cnblogs.com/tugenhua0707/p/4605593.html

欢迎纠正和更好方法;

移动端h5实现拍照上传图片并预览

标签:cap   sky   基本   append   转换   upload   ash   length   ext   

原文地址:http://www.cnblogs.com/sheqiuluo/p/7061278.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!