vue实现pc端拍照上传功能
程序员文章站
2022-04-06 22:41:00
本文实例为大家分享了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); } ); } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。