orbnexus
orbnexus

Reputation: 807

Saving image from canvas in server through Jquery and PHP

I am trying to store Canvas image to server through PHP I can see the file but it shows 0 bytes. Can you please help me to fix this issue.

Here is my code below:

HTML:

<img id="image" src="data:image/png;base64,iVBORw0K..." />

JQUERY:

$('.submit').unbind().click(function(){
var dataURL = $('#img').attr('src');
 $.ajax({
  type: "POST",
  url: "saveimage.php",
  dataType: 'json',
  cache: false,
  data: { 
   imgBase64: dataURL
  }
 });
});  

PHP:

$upload_dir = "../images/";
$img = $_POST['data'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = $upload_dir."image_name.png";
file_put_contents($file, $data);

Upvotes: 0

Views: 1501

Answers (1)

ɢʀᴜɴᴛ
ɢʀᴜɴᴛ

Reputation: 32889

It should be $img = $_POST['imgBase64'] not $img = $_POST['data'] in your php

as your data object 's key name is imgBase64 when sending the ajax post request

Upvotes: 2

Related Questions