I've been attempting to upload an image from a canvas to a server using ajax, but every time I end up with an empty image file that is only 879 bytes. I can't seem to figure out what I'm doing wrong. If someone could take a look, I would greatly appreciate it.
document.getElementById('input').addEventListener("change",function (e) {
var file = e.target.files[0];
var reader = new FileReader();
var output = document.getElementById('test');
reader.onload = function () {
var data = this.result;
var img = new Image();
img.src = data;
img.onload = function() {
var ctx = canvas.getContext("2d");
output.innerHTML = 'width: ' + img.width + '\n' + 'height: ' + img.height;
ctx.drawImage(img, 0, 0, img.width, img.height);
};
};
reader.readAsDataURL(file);
var canvasData = canvas.toDataURL("image/png");
Below is the Ajax code
$.ajax({ type: "POST", url: "upload_images.php", data: { canvasData:canvasData }, success:function() { } });
$upload_dir = 'uploads/'; //you will need to implement this function yourself
$img = $_POST['canvasData'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = $upload_dir."image_name.png";
$success = file_put_contents($file, $data);
header('Location: '.$_POST['return_url']);