简体   繁体   中英

Uploading an image from canvas to PHP server using AJAX

In the software I am building, I am using the webcam to take a picture and from there upload it to the PHP server for later usage. I have successfully uploaded images from my computer to the server using a form, but since the image I want to upload is already pre-decided, I've been looking into using AJAX. My code for taking the snapshot from the webcam is as follows:

 var video = document.getElementById('video');

        // Get access to the camera!
        if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
            // Not adding `{ audio: true }` since we only want video now
            navigator.mediaDevices.getUserMedia({video: true}).then(function (stream) {
                video.src = window.URL.createObjectURL(stream);
                video.play();
            });
        }

        // Elements for taking the snapshot
        var canvas = document.getElementById('canvas');
        var context = canvas.getContext('2d');
        var video = document.getElementById('video');

        // Trigger photo take
        document.getElementById("snap").addEventListener("click", function () {
            var img = context.drawImage(video, 0, 0, 640, 480);
        });

        document.getElementById("capture").addEventListener("click", function () {
            context.drawImage(video, 0, 0, 640, 480);
            //var capture = canvas.toDataURL();
        });

This is my php code which saves this image:

  <?php
    if (isset($_POST['upload'])) {
        $image_name = $_FILES['image']['name'];
        $image_name = $_FILES['image']['type'];
        $image_name = $_FILES['image']['size'];
        $image_tmp_name = $_FILES['image']['tmp_name'];

        if ($image_name == '') {
            echo "<script>alert('Please select an image.')</script>";
            exit();
        } else {
            move_uploaded_file($image_tmp_name, "pictures/$image_name");
            echo "Image uploaded succesfully.";
            echo "<img src= 'pictures/$image_name'>";
        }
    }
    ?>

I am sure that both of these bits of code work since I have tested them separately. As stated before, I am trying to tie them together using AJAX. The sample code I found for this is:

function saveImage() {
            var capture = canvas.toDataURL("image/png");
            var xmlHttpReq = false;
            if (window.XMLHttpRequest) {
                ajax = new XMLHttpRequest();
            }

            else if (window.ActiveXObject) {
                ajax = new ActiveXObject("Microsoft.XMLHTTP");
            }
            ajax.open('POST', 'picture.php', false);
            ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            ajax.onreadystatechange = function () {
                console.log(ajax.responseText);
            }
            ajax.send("imgData=" + capture);
        }

I used onClick = "saveImage()" within a button to try a call the function an upload the image to the server. When I hit the button, the file doesn't seem to access the server at all. Is there something I am missing here to make it all work?

You are not sending it as a file to send it as one use Blob or File object

var blob = new Blob([capture ], {type: 'application/octet-binary'});
var form = new FormData();
var fileName = 'snap.png';    //filename
form.append('something', blob, fileName);

On server decode and save

$dest = 'uploads/'.$_FILES['something']['name'];

move_uploaded_file($_FILES['something']['tmp_name'],$dest);
$file = file_get_contents($dest);
$tmp = explode(',',$file);                       //remove data: header
file_put_contents($dest,base64_decode($tmp[1])); //decode base64 n save
// Create a blob instead of dataURL (that way you save ~3x bandwidth and CPU)
canvas.toBlob(function(blob) {
  var fd = new FormData()

  // append the blob to a multipart form
  fd.append('image', blob, 'snapshot.png')

  // send the form to the server using ajax
  fetch('picture.php', {method: 'post', body: fd})
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM