使用Ajax和PHP上传图像

时间:2015-03-26 02:59:39

标签: javascript php jquery ajax post

我想在用户点击按钮(#myid.save)时上传图片.Below是我的代码:

HTML代码:

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

JavaScript代码:

$('#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文件:

<?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.'; 
?>

我的控制台说“已保存”,但我的服务器中没有保存图像。我在哪里错过了?

1 个答案:

答案 0 :(得分:0)

testSave.php引用$_POST['canvasData'],但JS将目标变量发送为imgBase64。该行应改为读取$img = $_POST['imgBase64']以匹配AJAX。