0

I'm trying to create an img object from canvas element and upload the image to the server:

  var img = new Image();
  img.src = c2.toDataURL("image/jpeg", 0.95);  // c2 is the canvas element
  var formData = new FormData();
  formData.append('img', img);
  $.ajax({
      url: 'pro01.php',
      cache:false,
      contentType: false,
      processData: false,
      type: 'post',
      data: formData,
      success: function(data) {
        console.log(data);
      }
  });

pro01.php

$img = $_FILES['img'];
$target_dir = "images/";
$target_file = $target_dir . basename($_FILES["img"]["name"]);
move_uploaded_file($_FILES["img"]["tmp_name"], $target_file);

Console: <b>Notice</b>: Undefined index: img in...

Any help?

qadenza
  • 9,025
  • 18
  • 73
  • 126
  • Possible duplicate of [PHP+JS: How to do Fileuploads in HTML Form as Content-Type Multipart (via JS)?](http://stackoverflow.com/questions/34711715/phpjs-how-to-do-fileuploads-in-html-form-as-content-type-multipart-via-js) – Kaiido Mar 13 '17 at 03:03

1 Answers1

1

Instead on making it an image just convert the canvas to base64:

var canvas = document.getElementById('myCanvas');
var dataURL = canvas.toDataURL();

Now send it:

$.ajax({
  type: "POST",
  url: "pro01.php",
  data: { 
     imgBase64: dataURL
  }

To receive it in php (pro01.php):

Get it from the post request, remove the start and call base64_decode() on the posted value:

$img = $_POST['imgBase64'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$fileData = base64_decode($img);
//saving
$fileName = 'photo.png';
file_put_contents($fileName, $fileData);
Noah Cristino
  • 757
  • 8
  • 29