2017-07-19 235 views
0

使用Photo Booth by vamapaull 我想捕捉image.with我的sql中的圖像它工作正常,但將其更改爲mysqli無法upload.webcam採取快照,但不存儲圖像文件夾。(在wamp上)。從存儲的圖像中識別幻燈片顯示。使用php上傳文件夾創建文件路徑

Table name uploadimages :: ID Name image user_id 
    veiw.php 
============================ 
<script type="text/javascript"> 
    hs.graphicsDir = 'graphics/'; 
    hs.align = 'center'; 
    hs.transitions = ['expand', 'crossfade']; 
    hs.wrapperClassName = 'dark borderless floating-caption'; 
    hs.fadeInOut = true; 
    hs.dimmingOpacity = .75; 

    // Add the controlbar 
    if (hs.addSlideshow) hs.addSlideshow({ 
     //slideshowGroup: 'group1', 
     interval: 5000, 
     repeat: false, 
     useControls: true, 
     fixedControls: 'fit', 
     overlayOptions: { 
      opacity: .6, 
      position: 'bottom center', 
      hideOnMouseOut: true 
     } 
    }); 
</script> 
<script src="swfobject.js" language="javascript"></script> 
     <script type="text/javascript"> 
      var flashvars = {}; 

      var parameters = {}; 
      parameters.scale = "noscale"; 
      parameters.wmode = "window"; 
      parameters.allowFullScreen = "true"; 
      parameters.allowScriptAccess = "always"; 

      var attributes = {}; 

      swfobject.embedSWF("take_picture.swf", "main", "700", "400", "9", 
        "expressInstall.swf", flashvars, parameters, attributes); 
     </script> 

     <script type="text/javascript"> 
      var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www."); 
      document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E")); 
     </script> 

     <script type="text/javascript"> 
      var pageTracker = _gat._getTracker("UA-3097820-1"); 
      pageTracker._trackPageview(); 
     </script> 
     <script type="text/javascript"> 
    var mainswf = new SWFObject("take_picture.swf", "main", "600", "400", "9", "#ffffff"); 
    mainswf.addParam("scale", "noscale"); 
    mainswf.addParam("wmode", "window"); 
    mainswf.addParam("allowFullScreen", "true"); 
    //mainswf.addVariable("requireLogin", "false"); 
    mainswf.write("flashArea"); 

</script> 

php code 

<?php 
    session_start(); 
    //This project is done by vamapaull: http://blog.vamapaull.com/ 
    include_once('db.php'); 
    if(isset($GLOBALS["HTTP_RAW_POST_DATA"])){ 
     $jpg = addslashes($GLOBALS["HTTP_RAW_POST_DATA"]); 
     $img = addslashes($_GET["img"]); 
     //$id= $_GET["id"]; 
     $vid=$_SESSION['vid']; 
     //$image =addslashes(file_get_contents($_FILES["img"]["tmp_name"])); 
     //$image_name = addslashes($_FILES["image"]["name"]); 
     $filename = "images/poza_". mktime(). ".jpg"; 
     file_put_contents($filename, $jpg); 
     mysqli_query($db ,"INSERT INTO uploadimages (Name,image,user_id) VALUES ('$filename','$jpg','$vid')")or die(mysqli_error($db)); 
     } else{ 
     echo "Encoded JPEG information not received."; 
    } 
    ?> 

------------------------- 
Other files can be seen at link given 
http://vamapaull.com/photo-booth-flash-webcam-image-capture/ This how directory looks like.image attached. 

Directory looks like this

+0

如果問題出現在「m」 ysqli'那麼你應該發佈你使用的php代碼而不是javascript – RamRaider

+0

所以 - 讓我理解正確。自從將數據庫api從mysql更改爲mysqli後,您將無法再上傳圖像 - 也無法在數據庫中記錄上傳數據? – RamRaider

+0

您是否曾嘗試通過添加'exit($ somevar)'語句或類似語句來查看PHP在任何點的調試情況?在PHP錯誤日誌中是否有任何錯誤?我要說的一件事是,由於許多安全缺陷,你應該考慮使用一些新的HTML5方法,而不是使用'Flash',因爲大多數瀏覽器不再支持Flash(它們仍然運行它,但不會很長) – RamRaider

回答

0

,而不是依賴於一種過時的,很快就被人遺忘的技術,如Flash可以考慮使用一些新的HTML5方法(?) - 現在有很多網站的API在Javascript使多媒體設備工作相對簡單並具有相當好的跨瀏覽器支持的核心。

以下兩個腳本(可以合併爲一個)應該給出一個想法,即如何使用所述技術完成您的任務 - 並且將數據保存到數據庫的部分使用prepared statement,因此不應該存在重大的風險SQL注入儘可能與您的原始,失敗,代碼。

<!-- 
    html5_snapshot.php 
    ------------------ 
--> 
<!DOCTYPE html> 
<html> 
    <head> 
     <meta charset='utf-8'> 
     <title>Webcam snapshots</title> 
     <style> 
      body{ 
       padding:3em;  
      } 
      #media, 
      #buttons, 
      #results{ 
       box-sizing:border-box; 
       width:80%; 
       margin:1rem auto; 
       float:none; 
       text-align:center; 
      } 
      video,canvas{ 
       margin:2rem auto; 
       border:1px solid black; 
       border-radius:10px; 
       display:inline-block; 
       position:relative; 
       float:none; 
       clear:none; 
       width:320px; 
       height:240px; 
      } 
      h1{ 
       text-shadow: 1px 1px 2px black, 0 0 1em blue, 0 0 0.2em blue; 
       color: white; 
       width:80%; 
       margin:0 auto 0 auto!important; 
       float:none; 
       font: 1.5em verdana; 
       text-align:center; 
      } 
      #results{ 
       font-size:0.7rem; 
      } 
     </style> 
     <script> 
      window.addEventListener('DOMContentLoaded', function(e) { 
       (function() { 
        /* edit path to suit */ 
        var handler='html5_snapshot_handler.php'; 
        /* establish main variables */ 
        var streaming = false, 
         oSave   = document.getElementById('save'), 
         oClear  = document.getElementById('clear'), 
         oGrab   = document.getElementById('grab'), 
         video   = document.getElementById('video'), 
         canvas  = document.getElementById('canvas'), 
         width = 640, 
         height = 480; 

        var basicOptions={ 
         video: true, 
         audio: false 
        }; 
        /* callback for previous method-no longer used 
        function gotvideo(stream){ 
         if(navigator.mozGetUserMedia) { 
          video.mozSrcObject = stream; 
         } else { 
          var vendorURL = window.URL || window.webkitURL; 
          video.src = vendorURL.createObjectURL(stream); 
         } 
         video.play(); 
        } 
        */ 
        function report(msg){ 
         var ctx=canvas.getContext('2d'); 
          ctx.font='2em verdana'; 
          ctx.fillStyle='red'; 
          ctx.textAlign='center'; 
          ctx.textBaseline='middle'; 
          ctx.fillText(msg, Math.abs(canvas.width * 0.5), Math.abs(canvas.height * 0.5)); 
         console.warn(msg); 
        } 
        function setproperties(e){ 
         if(!streaming) { 
          video.width=width; 
          video.height=height; 
          canvas.width=width; 
          canvas.height=height; 
          streaming = true; 
         } 
        } 
        function takepicture(e) { 
         e.preventDefault(); 
         var ctx=canvas.getContext('2d'); 
          ctx.drawImage(video, 0, 0, width, height); 
        } 
        function cbsaveimage(evt){ 
         /* 
          The ajax callback function - currently only shows 
          the returned json data but could do something 
          much more useful 
         */ 
         document.getElementById('results').innerHTML=(this.status == 200) ? this.response : 'error: '+this.status;  
        } 
        function saveimage(e){ 
         var el=e.target; 
         var data=canvas.toDataURL('image/png').replace(/^data:image\/(png|jpg);base64,/, ''); 


         if(!isBlankCanvas(canvas)){ 
          var fd=new FormData(); 
           fd.append('data', data); 

          var req = new XMLHttpRequest(); 
           req.addEventListener('load', cbsaveimage, false); 
           req.open('POST', handler, true); 
           req.send(fd); 

         } else { 
          var bttns=[ oSave, oGrab, oClear ]; 

          bttns.forEach(function(e,i,a){ 
           e.disabled=true; 
          }); 
          setTimeout(function(){ 
           bttns.forEach(function(e,i,a){ 
            e.disabled=false; 
           }); 
           canvas.getContext('2d').clearRect(0,0, width, height); 
          },2500); 

          report('Nothing to upload'); 
         } 
        } 
        function clearcanvas(evt){ 
         canvas.getContext('2d').clearRect(0,0, width, height); 
        } 
        function isBlankCanvas(canvas) { 
         var blank=document.getElementById('empty'); 
          blank.width=canvas.width; 
          blank.height=canvas.height; 
         return canvas.toDataURL() == blank.toDataURL(); 
        } 


        /* Listeners */ 
        oSave.addEventListener('click', saveimage, false); 
        oClear.addEventListener('click', clearcanvas, false); 
        oGrab.addEventListener('click', takepicture, false); 
        video.addEventListener('canplay', setproperties, false); 

        /* 
         navigator.getMedia = (navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia); 
         navigator.getMedia(basicOptions, gotvideo, report); 

         The above method is deprecated (still works in certain browsers however) 
         but neither the above or the newer method below will work in Internet Exploder 
         The below should work in Firefox,Chrome & Opera. 

        */ 

        try{ 
         navigator.mediaDevices.getUserMedia(basicOptions) .then(function(stream) { 
          video.srcObject = stream; 
          video.onloadedmetadata = function(e) { 
           video.play(); 
          }; 
         }).catch(function(err) { console.log(err.name + ": " + err.message); }); 
        }catch(error){ 
         console.log(error); 
        } 

       })(); 
      },false); 
     </script> 
    </head> 
    <body> 
     <h1>Webcam snapshots</h1> 
     <div id='media'> 
      <video id='video'></video> 
      <canvas id='canvas'></canvas> 
      <canvas id='empty' style='display:none' width=100 height=100></canvas> 
     </div> 
     <div id='buttons'> 
      <input type='button' id='grab' value='Take snapshot' /> 
      <input type='button' id='save' value='Save Snapshot' /> 
      <input type='button' id='clear' value='Clear canvas' /> 
     </div> 
     <pre id='results'></pre> 
    </body> 
</html> 


<?php 
    /* 

     html5_snapshot_handler.php 
     -------------------------- 
    */ 

    session_start(); 

    if($_SERVER['REQUEST_METHOD']=='POST' && isset($_POST['data'])) { 
     /* variable to register if db call is successful or not */ 
     $result=false; 

     /* As the image does not have a name, create a name of some sort */ 
     $filename=uniqid('snapshot').'_'.time().'.png'; 

     /* The path on the server where the upload is to be stored. */ 
     $uploadpath='c:/temp/fileuploads/2/'; 

     /* Final path for uploaded image */ 
     $filepath=$uploadpath . $filename; 

     /* Get the file "data" */ 
     $data = filter_input(INPUT_POST, 'data', FILTER_SANITIZE_SPECIAL_CHARS); 

     /* write to a new file */ 
     $bytes = file_put_contents($filepath, base64_decode($data)); 

     /* Save to database */ 
     $dbhost = 'localhost'; 
     $dbuser = 'root'; 
     $dbpwd = 'xxx'; 
     $dbname = 'stack'; 

     $db = new mysqli($dbhost, $dbuser, $dbpwd, $dbname); 
     $sql='insert into `uploadimages` (`name`,`image`,`user_id`) values (?,?,?);'; 
     $stmt=$db->prepare($sql); 
     if($stmt){ 
      $stmt->bind_param('ssi', $name, $image, $uid); 
      /* 
       It would be wise to store just the path to the image 
       as the file is being uploaded anyway so you do not need 
       to store a BLOB - over time it would take up a huge 
       amount of diskspace on the database server 
      */ 
      $name=$filename; 
      $image=$filepath; 
      $uid=$_SESSION['vid']; 

      $result = $stmt->execute(); 
      $stmt->free_result(); 
      $stmt->close(); 
      $db->close(); 
     } 

     /* send something back to the client - callback */ 
     header('Content-Type: application/json'); 
     exit(json_encode(array(
      'filename' => $filename, 
      'filepath' => $filepath, 
      'filesize' => $bytes, 
      'status' => realpath($filepath) ? 1 : 0, 
      'db'  => $result 
     ))); 
    } 


    /* If the request is other than POST - report an error */ 
    exit(header('HTTP/1.1 404 Not Found', true, 404)); 

?> 

時間認輸 - 我一直沒能得到以上IE11工作(雖然我相信有上GithubwebRTC4allTemasys WebRTC可用polyfills但我已經試過無那些我敢肯定在其他地方還會有其他的polyfill

早在90年代初,當Internet Explorer在瀏覽器市場佔據主導地位時,我們就喜歡用IE編碼,並且總是發現Netscape Navigator會拋出各種各樣的錯誤 - 現在儘管它是角色逆轉

+0

對不起它不explorer10 – user2939942

+0

我NT越來越像使用代碼'<?PHP \t \t $ lastID = mysqli_query($分貝, '從uploadimages選擇*其中USER_ID =「'。$ _ REQUEST [ 'id']。'「ORDER BY ID DESC LIMIT 1'); $ las = mysqli_fetch_array($ lastID)或die(mysqli_error($ db)); $ rea = $ las ['ID']; $ image = mysqli_query($ db,「SELECT * FROM uploadimages WHERE ID ='」。$ rea。「'」); $ images = mysqli_fetch_array($ image)或die(mysqli_error($ db)); \t \t echo'​​' 。 '' 。 ''; \t \t?>另外,如果vamapaull可以完成 – user2939942

+0

它在哪裏與IE10失敗? Javascript中是否存在錯誤(forEach也許)?至於「沒有獲取代碼的圖像」 - 我發佈的php cpde存儲上傳文件的路徑名,而不是RAW文件數據本身,因爲正如我所提到的那樣,這樣做形式不佳,會佔用大量磁盤空間db服務器。你將不得不''base64_encode(file_get_contents($ images ['image']))' – RamRaider