Michelle
Michelle

Reputation: 57

base64 image post to php results in empty file

My question is very similar to one at this thread. I'm creating a canvas element on the fly, adding one or more img elements to it, and posting each img in turn to a php script on the server that then saves the resulting file. It's a basic drag-and-drop operation for images, much like Facebook's or the one on G+. I have everything working correctly except that the files resulting from the upload and save are all empty-- or rather, they're 2kb each and display nothing but blackness.

Here's the relevant portions of the code: HTML:

    <form method="post" action="upload.php" id="formUpload">
    <div id="op">
        <label class="lbl">Drop images here to add them,<br>or click an image to see it enlarged</label>
        <span style='display:inline-block'>
            <input type="file" name="files[]" id='file' class="fileUpload" onchange="startRead()" multiple><br>
            <input type='submit' name='submit' value='+' class="fileUpload">
        </span>
    </div>
</form>

(not bothering with CSS as it's not germane to this)

javascript/jquery:

function addImg(imgSrc) {
    var canvas = document.createElement('canvas');
    var context = canvas.getContext('2d');
    var imageObj = new Image();

    imageObj.onload = function() {
        context.drawImage(imageObj, 5, 5);
    };

    imageObj.className = "imgThumbnail";

    imageObj.style.width = 140 + "px";
    imageObj.style.height = 140 + "px";

    imageObj.src = imgSrc.currentTarget.result;
    var dataURL = canvas.toDataURL();

    $.ajax({
        type: "POST",
        url: "upload.php",
        data: { 
           imgBase64: dataURL
        }
    }).done(function(data) {
        var fileName = data;
        if (fileName.substring(1,1) !== "!") {
            document.getElementById('op').insertBefore(imageObj);
            $("#op").on('click', 'img', imgEnlarge);
            $.get($("#path").val() + "/includes/addImage.php", {
                imageType: $("#imageType").val(),
                idParentObject: $("#idParentObject").val(),
                url: fileName
            });        
        } else {
            alert("Error in upload processs.  Could not save " + data.substring(2, data.length-1) + ".");
            imageObj.attr("src", "../images/missing.png");
        }
    });   
} 

PHP:

define('UPLOAD_DIR', '../images/');

$img = $_POST["img"];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);

$data = base64_decode($img);

$file = UPLOAD_DIR . uniqid() . '.png';
$success = file_put_contents($file,$data);

print $success ? $file : '!$file';

Any help figuring out what I'm missing will be greatly appreciated. Correct answers will be even more appreciated.

Upvotes: 1

Views: 1358

Answers (1)

Michelle
Michelle

Reputation: 57

Got it. It was an order of operations error. I was posting the canvas's base64 representation prior to drawing the image onto it. Here's what the javascript looks like corrected:

function addImg(imgSrc) {
    var canvas = document.createElement('canvas');
    var context = canvas.getContext('2d');
    var imageObj = new Image();

    imageObj.className = "imgThumbnail";

    imageObj.style.width = 140 + "px";
    imageObj.style.height = 140 + "px";

    imageObj.src = imgSrc.currentTarget.result;
    context.drawImage(imageObj, 0, 0, 140, 140);

    var dataURL = canvas.toDataURL('image/png');                

    $.ajax({
        type: "POST",
        url: $("#path").val() + "/includes/upload.php",
        data: { 
           img: dataURL
        }                    
    }).done(function(data) {
        var fileName = data;
        if (fileName.substring(1,1) !== "!") {
            document.getElementById('op').insertBefore(imageObj);
            $("#op").on('click', 'img', imgEnlarge);
            $.get($("#path").val() + "/includes/addImage.php", {
                imageType: $("#imageType").val(),
                idParentObject: $("#idParentObject").val(),
                url: fileName
            });   
            $("#testOutput").val(data);
            $("#testOutput").show();
        } else {
            alert("Error in upload processs.  Could not save " + data.substring(2, data.length-1) + ".");
            imageObj.attr("src", "../images/missing.png");
        }
    });   
}

Upvotes: 1

Related Questions