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

时间:2020-06-25 15:26:39

标签: javascript php html ajax base64

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

CV_8UC3

和一些JS:

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

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

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

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

2 个答案:

答案 0 :(得分:1)

您的代码存在一些问题。

参数错误

第一个问题是您以imgBase64的形式发布数据,但尝试通过$_POST['upload'].来获取数据

由于您没有发布任何名为upload的内容,因此您的if语句if (isset($_POST['upload']))将始终为false,并且if中的代码将永远不会执行。

改为使用$_POST['imgBase64']

base64字符串

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

这不是base64编码数据的一部分,因此您需要先从字符串中删除该部分,然后再尝试对其进行解码。

应该是这样的:

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

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

答案 1 :(得分:0)

示例代码

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