H5实现拍照上传功能

来源:互联网 发布:网络抢房 编辑:程序博客网 时间:2024/05/21 16:58
页面样式:
  1. 上传图片有原生的方法<input type="file" accept="image/*">,如果只想要拍照上传,不希望用户选择图片上传,可以通过添加capture属性,该属性值有camcorder/microphone/camera...,此处选择camera。PS:该属性存在浏览器兼容性问题,不是所有的浏览器都支持。
    <input type="file" accept="image/*" capture="camera" >
  2. 因为原生file样式不满足要求,需要进行相应的处理,此时使用定位,在input上面放置我们想要的页面效果。然后当点击上面的元素,就可以触发我们的input进行图片上传。此时的问题是:当点击input上面的元素,需要事件穿透,即相当于点击input。则借助于css3新属性pointer-events。
    //使用cursor进行事件穿透,来阻止元素成为鼠标事件的目标button{     cursor:pointer;     pointer-events:none;}

    ----此时图片上传的样式已经处理好了----

    代码片段:
    <style >    *{        padding: 0;        margin: 0;    }    .wrapper{        width: 320px;        height: 50px;        margin: 20px auto;        position: relative;        border: 1px solid #f0f0f0;    }    input{        width: 100px;        height: 30px;    }    button{        position: absolute;        cursor: pointer;        pointer-events: none;        width: 100px;        height: 30px;        left: 0;        top: 0;    }    a{        pointer-events: none;    }    .img{        border: 1px solid #ccc;        padding: 10px;    }</style ><form action="${pageContext.request.contextPath}/files/fileUpload" method="post" enctype="multipart/form-data" id="uploadvideoid"><div class = "wrapper">     <input type = "file" accept= "image/*" capture= "camera" id= "img" />     <button >上传照片 </button ></form>

    </div >

想要预览的话加上<img id="portrait" src="" width="70" height="75"> 

 js

通过change事件,监听图片上传,通过readerAsDataURL获取上传的图片。

document.getElementById( 'img').addEventListener( 'change', function () {     var reader = new FileReader();     reader.onload = function (e) {         document.getElementById("portrait").src = e.target.result; $("#uploadvideoid").ajaxSubmit(); //这个是ajax提交表单记得加上<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-form.js"></script>     };     reader.readAsDataURL(this.files[0]);        var fileSize = Math.round( this.files[0].size/1024/1024) ;      }, false);
控制层



还是没成功的联系我QQ392716797找原因

@RequestMapping("fileUpload")
public void fileUpload(@RequestParam("file") MultipartFile file) {
System.out.println("jrff");
// 锟叫讹拷锟侥硷拷锟角凤拷为锟斤拷
if (!file.isEmpty()) {
try {
// 锟侥硷拷锟斤拷锟斤拷路锟斤拷
String filePath = request.getSession().getServletContext()
.getRealPath("/")
+ "upload/weike/" + file.getOriginalFilename();
// 转锟斤拷锟侥硷拷
file.transferTo(new File(filePath));
} catch (Exception e) {
e.printStackTrace();
}
}
// 锟截讹拷锟斤拷
/*return "redirect:/list.html";*/
}