简体   繁体   中英

Upload an Image using Ajax and PHP

I want to upload an image when the user clicks a button(#myid.save).Below is my code:

HTML Code:

<canvas id="cnv" width="500" height="100"></canvas>
<input id="myid_save" type="submit">Save</input>

JavaScript Code:

$('#myid_save').on('click', function(e) {        
    e.preventDefault();
    saveViaAJAX();        
}); 

function saveViaAJAX()
{
    var testCanvas = document.getElementById("cnv");
    var canvasData = testCanvas.toDataURL("image/png");
    //var postData = "canvasData="+canvasData;

    $.ajax({
      type: "POST",
      url: "testSave.php",
      data: { 
         imgBase64: canvasData
      }
    }).done(function(o) {
      console.log('saved');                 
    });
}

testSave.php File:

<?php

    define('UPLOAD_DIR', 'C:\xampp\htdocs\drupal-7.34\sites\all\modules\myid\uploads\id_signature');
    $img = $_POST['imgBase64'];
    $img = str_replace('data:image/png;base64,', '', $img);
    $img = str_replace(' ', '+', $img);
    $data = base64_decode($img);
    $file = UPLOAD_DIR . '\sample.png';
    $success = file_put_contents($file, $data);
    print $success ? $file : 'Unable to save the file.'; 
?>

My console says "saved" but there's no image saved in my server. Where am I missing?

testSave.php references $_POST['canvasData'] , but the JS sends the intended variable as imgBase64. That line should instead read $img = $_POST['imgBase64'] in order to match the AJAX.

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