2017-02-22 49 views
0

這是我的js代碼AJAX不會帆布數據發送到PHP

(function(){ 
    var video = document.getElementById('video'), 
    canvas = document.getElementById('canvas'), 
    context = canvas.getContext('2d'), 
    photo = document.getElementById('photo'), 
    vendorUrl = window.URL || window.webkitURL; 
    datas = canvas.toDataURL('images/png'); 

    navigator.getMedia = navigator.getUserMedia || 
          navigator.webkitGetUserMedia || 
          navigator.mozGetUserMedia || 
          navigator.msGetUserMedia; 

    navigator.getMedia({ 
     video: true, 
     audio: false 
    }, function(stream){ 
     video.src = vendorUrl.createObjectURL(stream); 
     video.play(); 
    }, function(error){ 

    }); 

    document.getElementById('capture').addEventListener('click',function(){ 
     context.drawImage(video, 0, 0, 400, 300); 
     photo.setAttribute('src', canvas.toDataURL('images/png')); 


     datas = canvas.toDataURL('images/png'); 



    }); 
    var canvasData = canvas.toDataURL("image/png"); 
     var ajax = new XMLHttpRequest(); 
     ajax.open("POST",'webcam.php',false); 
     ajax.setRequestHeader('Content-Type', 'application/upload'); 
     ajax.send(canvasData); 


})(); 

這是PHP代碼接收

<?php 

    if (isset($GLOBALS["HTTP_RAW_POST_DATA"])) 
{ 
    echo "true"; 
    // Get the data 
    $imageData=$GLOBALS['HTTP_RAW_POST_DATA']; 

    // Remove the headers (data:,) part. 
    // A real application should use them according to needs such as to check image type 
    $filteredData=substr($imageData, strpos($imageData, ",")+1); 

    // Need to decode before saving since the data we received is already base64 encoded 
    $unencodedData=base64_decode($filteredData); 

    //echo "unencodedData".$unencodedData; 

    // Save file. This example uses a hard coded filename for testing, 
    // but a real application can specify filename in POST variable 
    $fp = fopen('test.png', 'wb'); 
    fwrite($fp, $unencodedData); 
    fclose($fp); 
} 
?> 

<head> 
    <meta charset="UTF-8"> 
    <Title>Document</title> 

    <link rel="stylesheet" href="css/main.css"> 
    </head> 
    <body> 

     <div class="booth"> 
      <video id = "video" width="400" height="300"></video> 
      <a href="#" id ="capture" class="booth-capture-button">Snap Shot</a> 
      <canvas id="canvas" width="400" height="300"></canvas> 
      <img id ="photo" name = "photo" src="images/events/default.png" alt="Photo of you"> 
     </div> 

    <script src="js/photo.js"></script> 
    </body> 

<?php 


?> 

申請打算採取的快照數據用戶並通過javascript保存照片。我試圖找到一種方法將數據發送回php並將其用於保存到數據庫中。我知道它保存在base64編碼中。我嘗試了不同的Ajax方法,包括我保存的方法,但數據往往不會將任何數據發送到php文件夾。

謝謝你在先進。

回答

0

我只是建議你檢查你的一些代碼點:

  1. 形式的內容類型。要上傳文件,您必須使用「multipart/form-data」

    ajax.setRequestHeader('Content-Type','multipart/form-data');

  2. 您可以使用FORMDATA類JS發送之前進行表單數據: https://developer.mozilla.org/en/docs/Web/API/FormData/append

  3. 畫布功能 「toDataURL」 沒有MIME類型 「圖像/ PNG」。只是「圖像/ PNG」

+0

沒有骰子,嘗試這兩種方法,並沒有發送到PHP。 – Jay