0

I'm working with AJAX, and I sent a request with POST, in that request I sent a canvas generated image (dataURL). When request is finished, returns in console the generated image in base64. I take all string of image data and I go to a webpage (https://codebeautify.org/base64-to-image-converter), in that page I put the image data, and well I get a the image generated perfectly.

Image Data in base64 to image converter

The problem is that the function file_put_contents writes a corrupted file. (In addition, the file weighs more than 0 bytes).

Corrupted file in save path

Well, I don't have any idea what I do wrong. Finally, here is the code and sorry for my bad english. Thanks :)

uploadThumbnail.php

<?php
session_start();
$img = $_REQUEST['imgBase64'];
$img = htmlspecialchars($img);
echo $img;
file_put_contents("../thumbnails/" . $_SESSION['uploadedVideoID'] .'.png', 
base64_decode($img));
?>

And, Caller script.

function generateThumbnail() {    

var thecanvas = document.getElementById('taco');
var context = thecanvas.getContext('2d');
context.drawImage(video, 0, 0, 256, 144);
var dataURL = thecanvas.toDataURL();

//create img
var img = document.createElement('img');
img.setAttribute('src', dataURL);

//append img in container div
document.getElementById('videoThumbnailContainer').appendChild(img);
  $.ajax({
    type: "POST",
    url: "upload/uploadThumbnail.php",
    data: { 
       imgBase64: dataURL
    }
  }).done(function(o) {
    console.log(o); 
});

}
  • Like I said, the content of `$_REQUEST['imgBase64'];` is basiclly the data generated with *canvas* and is sended via *.ajax Post*. It seems that the content is fine, since as I comment, when placing that content on the page to convert base64 into image, the image looks perfectly. – Diablo Rodriguez Apr 17 '18 at 01:45
  • Similar question has been asked & answered before. https://stackoverflow.com/questions/11511511/how-to-save-a-png-image-server-side-from-a-base64-data-string – Matthew Apr 17 '18 at 01:47
  • @Matthew Uff, finally! I want to cry... thank you very much :'D. I do not know why I did not find that question before really. And now, how do you frame your answer as correct? – Diablo Rodriguez Apr 17 '18 at 01:51

0 Answers0