简体   繁体   中英

Uploading image created from canvas

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?

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);

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