vue实现pc端拍照上传功能
作者:qq_39070698
这篇文章主要为大家详细介绍了vue实现pc端拍照上传功能,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
本文实例为大家分享了vue实现pc端拍照上传功能的具体代码,供大家参考,具体内容如下
<!DOCTYPE html> <html> <head> <meta charset="UTF8"> </head> <body> <div id="contentHolder"> <video id="video" width="320" height="320" autoplay></video> <button id="camera">拍照</button> <canvas id="canvas" width="320" height="320"> </canvas> </div> <script type="text/javascript"> var video = document.getElementById('video'); var track; var Camera= document.getElementById('camera'); window.addEventListener("DOMContentLoaded", function(){ navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia; if (navigator.getUserMedia) { navigator.getUserMedia({video:true}, function(stream) { track = stream.getTracks()[0]; // 通过这个关闭摄像头 video.src = window.URL.createObjectURL(stream); video.onloadedmetadata = function(e) { video.play(); }; }, function(err) { alert(err.name); } ); } }); Camera.onclick = function(){ var canvas = document.getElementById('canvas'); var context2D = canvas.getContext("2d"); context2D.fillStyle = "#ffffff"; context2D.fillRect(0, 0, 320, 320); context2D.drawImage(video, 0, 0, 320, 320); var image_code =canvas.toDataURL("image/png");//要传给后台的base64 console.log(image_code) if (null != track) { track.stop();//关闭摄像头 } }; </script> </body> </html>
上段代码会在打开网页的时候就会调用摄像头
传给后台的是个base64码
下面是我用vue传给后台的代码
var param = { file:image_code2 } var a = JSON.stringify(param); uploadimg(a).then((res) => { console.log(res); });
下面是我的php后台接收代码
public function uploadImg($name="img",$path='img'){ $_POST = json_decode(file_get_contents('php://input'),true); $param = $_POST; $image_code = $param['file']; $img = str_replace('data:image/png;base64,', '', $image_code);//获取base64码 $img = str_replace(' ', '+', $img); $data = base64_decode($img); $name = time().".png"; $savepath = "./upload/".$name;//将图片存到的位置 file_put_contents($savepath,$data);//将内容写入文件 $this->ajaxReturn(array('status'=>'0','data'=>$savepath)); }
如果想点击触发 打开摄像头可以将camera中代码取出放在一个方法中即可
var Camera= document.getElementById('camera'); window.addEventListener("DOMContentLoaded", function(){ navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia; }); function demo(){ if (navigator.getUserMedia) { navigator.getUserMedia({video:true}, function(stream) { track = stream.getTracks()[0]; // 通过这个关闭摄像头 video.src = window.URL.createObjectURL(stream); video.onloadedmetadata = function(e) { video.play(); }; }, function(err) { alert(err.name); } ); } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。