簡體   English   中英

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

它仍然沒有保存到我的文件夾中。 顯示兩個控制台日志。 我不知道如何解決或解決這個問題。 任何人都可以幫忙嗎?

您的代碼存在一些問題。

錯誤的參數

第一個問題是您將數據發布為imgBase64 ,但嘗試使用$_POST['upload'].

由於您沒有發布任何名為upload的內容,因此您的 if 語句: if (isset($_POST['upload']))將始終評估為 false,並且您在 if 中的代碼將永遠不會被執行。

改用$_POST['imgBase64']

base64 字符串

如果您查看發布的字符串的開頭,它可能以以下內容開頭: data:image/jpeg;base64, (添加該內容的是 js function 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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM