简体   繁体   中英

How Can Inline IMG SRC data:image Be Transferred With JavaScript to PHP?

Below is an element that contains inline base64 image data (abbreviated to fit here). How can JavaScript get the inline data and send it to PHP? It would be good if an intermediate canvas can be avoided, since the raw data is already available.

In the page:

<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEU4Xoy9WY9k6" id="photo">

The JavaScript I'm currently using to click on the element to trigger the transfer to PHP, which saves a 0 byte .png file to disk:

$("#photo").click(function() {
  var xhr = new XMLHttpRequest();
  xhr.open('POST', 'uploadPhoto.php', true);
  xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
  var data = 'image=' + this.src;
  xhr.send(data);
});

uploadPhoto.php, which receives the data and writes it to disk:

<?php
  if ($_POST) {
    define('UPLOAD_DIR', '/photos/');
    $img = $_POST['image'];
    $img = str_replace('data:image/jpeg;base64,', '', $img);
    $img = str_replace(' ', '+', $img);
    $data = base64_decode($img);
    $file = UPLOAD_DIR . uniqid() . '.png';
    $success = file_put_contents($file, $data);
    print $success ? $file : 'Unable to save the file.';
  } else {
    print 'Unable to save ' . $_POST['image'];
  }
?>

What's missing?

SOLUTION UPDATE

Per @EhsanT, the png format of the raw data was not matched in the php, so this line in the php now has png where jpeg used to be:

str_replace('data:image/png;base64,', '', $img);

The only thing you are doing wrong in this particular sample code you have provided is that you have a PNG base64 image data, and in your uploadPhoto.php file you are expecting a JPG file.

So in the uploadPhoto.php file just change this line:

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

to this:

$img = str_replace('data:image/png;base64,', '', $img);

and you are good to go

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