0

Im using webcam to capture user profile picture, and then i upload the image to server using XMLHttpRequest like so:

document.getElementById('upload').addEventListener('click', function () {
    var image = canvas.toDataURL('image/jpeg', 1.0);
    var request = new XMLHttpRequest();
    var fd = new FormData();
    fd.append('picture', image);
    request.open('POST', 'upload.php');
    request.onload = function () {
        if (request.status == 200) {
            console.log('all done: ');
        } else {
            console.log('Nope');
        }
    };
    request.setRequestHeader('Content-Type', 'multipart/form-data');
    request.send(fd);
});

Im not using a form, im getting image from canva html element in this line:

var image = canvas.toDataURL('image/jpeg', 1.0);

I think is all ok with the js part, the console shows that the data is sent. In php i try to manipulate the image and store to a server directory like so:

<?php
$info = pathinfo($_FILES['picture']['name']);
$ext = $info['extension']; // get the extension of the file
$newname = "perfil.".$ext; 

$target = 'uploads/'.$newname;
move_uploaded_file( $_FILES['picture']['tmp_name'], $target);
?>

But the image is nos actually stored in the folder specified in the code above, i dont know what im doing wrong or if something escaped me.

Bruno Estevao
  • 21
  • 1
  • 7

1 Answers1

1
var image = canvas.toDataURL('image/jpeg', 1.0);
                   ^^^^^^^^^

You are getting a data URL. This is not a file.

$info = pathinfo($_FILES['picture']['name']);

Since it isn't a file, it won't be in $_FILES or have a file name.

You can read the data from $_POST['picture']. This question then covers the process of converting a data URL to a file.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335