通过 AJAX 将 base64 图像保存到服务器

Save base64 image via AJAX to server

我想在 php 服务器上保存 base64 图像。 我正在使用 webcam-easy (https://github.com/bensonruan/webcam-easy)。 我在他的演示的 index.html 上插入了一个简单的按钮:

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

和一些 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);
        
        }

这就是我在 send.php 文件中收到 AJAX 的方式:

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

它仍然没有保存到我的文件夹中。显示两个控制台日志。我不知道如何排除故障或解决这个问题。有人可以帮忙吗?

您的代码存在一些问题。

参数错误

第一个问题是您 post 数据为 imgBase64 但试图用 $_POST['upload'].

获取它

因为您没有 posting 任何名为 upload 的东西,您的 if 语句:if (isset($_POST['upload'])) 将始终评估为 false,并且 if 中的代码永远不会被执行。

改用$_POST['imgBase64']

base64字符串

如果您查看 posted 字符串的开头,它可能以类似以下内容开头:data:image/jpeg;base64,(添加该内容的是 js 函数 toDataUrl())。

这不是 base64 编码数据的一部分,因此您需要在尝试解码之前从字符串中删除该部分。

应该是这样的:

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

您可能需要更改要替换的字符串以匹配您的字符串的开头。

示例代码

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