简体   繁体   中英

Save base64 image via AJAX to server

I want to save a base64 image on a php server. I am using webcam-easy ( https://github.com/bensonruan/webcam-easy ). I inserted aa simple button on the index.html of his demo:

<button id="upload" onClick="postData()" style="cursor: pointer;">Send!</button>

and some JS:

    function postData() {
var canvas = document.getElementById("canvas");
var dataURL = canvas.toDataURL("image/jpeg", 1.0);

$.ajax({
  type: "POST",
  url: "send.php",
  data: { 
     imgBase64: dataURL
  }
}).done(function(o) {
  console.log('saved'); 
  // If you want the file to be visible in the browser 
  // - please modify the callback in javascript. All you
  // need is to return the url to the file, you just saved 
  // and than put the image in your browser.
});
console.log(dataURL);
        
        }

This is how I recieve the AJAX in my send.php file:

if(isset($_POST['upload'])){
  $str= $_POST['upload'];
$str=base64_decode($str);
  file_put_contents('tmp/'. 'stuff.jpg', $str);
}

It still is not saved to my folder. Both console logs are displayed. I don't know how to troubleshoot or solve this. Can anyone help?

There are some issues with your code.

Wrong parameter

The first issue is that you post the data as imgBase64 but are trying to get it with $_POST['upload'].

Since you're not posting anything named upload , your if-statement: if (isset($_POST['upload'])) will always evaluate as false and your code inside the if will never be executed.

Use $_POST['imgBase64'] instead.

The base64 string

If you look at the beginning of the posted string, it probably starts with something like: data:image/jpeg;base64, (it's the js function toDataUrl() that adds that).

That is not part of the base64 encoded data so you need to remove that part from the string before trying to decode it.

It should be something like:

$str = str_replace('data:image/jpeg;base64,', '', $str);

You might need to change the string to replace to match what your string starts with.

sample Code

if(isset($_POST['upload']))
{
  $b64 = $_POST['upload'];
  $bin = base64_decode($b64);

  # Load GD resource from binary data
  $im = imageCreateFromString($bin);

  # Make sure that the GD library was able to load the image
  # This is important, because you should not miss corrupted or unsupported images
  if (!$im)
  {
    die('Base64 value is not a valid image');
  }

  # Specify the location where you want to save the image
  $img_file = '/files/images/filename.jpg';


  # To block any possible exploits, consider increasing the compression level
  imagejpeg($im, $img_file, 0);
}

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