【问题标题】:Sending image data using AJAX and store on server使用 AJAX 发送图像数据并存储在服务器上
【发布时间】:2016-01-27 11:30:44
【问题描述】:

PHP 没有从 ajax 接收数据,我正在尝试使用 canvas HTML5 创建图像并使用 PHP 将其存储在我的服务器上,但是当我这样做时,我什么也没有收到。

image.php:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<canvas width="800" height="420" id="canvas"></canvas>
<script>

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");

var img  = loadImage('images/quizes/sim.png' ,main);
var img1 = loadImage('images/users/alfred.jpg', main);
var img2 = loadImage('images/users/brynjar.jpg', main);


var imagesLoaded = 0;
function main() {
    imagesLoaded += 1;

    if(imagesLoaded == 3) {

        ctx.drawImage(img, 0, 0, 800, 420);

        ctx.drawImage(img1, 0, 0, 320, 320);

        ctx.drawImage(img2, 480, 0, 320, 320);

    }
}

function loadImage(src, onload) {
    var img = new Image();

    img.onload = onload;
    img.src = src;

    return img;
}

var dataURL = canvas.toDataURL();

alert(dataURL);

$.ajax({
    type: "POST",
    url: "script.php",
    data: {
        imgBase64: dataURL
    }
}).done(function(o) {
    console.log('saved');
    // If you want the file to be visible in the browser
    // - please modify the callback in javascript. All you
    // need is to return the url to the file, you just saved
    // and than put the image in your browser.
});
</script>

我也有 Script.php:

$img = $_POST['data'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$fileData = base64_decode($img);
//saving
$fileName = 'photo.png';
file_put_contents($fileName, $fileData);

但是当我运行 image.php 时,$_post['data'] 没有获取任何数据。

【问题讨论】:

  • 尝试读取$_POST['imgBase64']变量。如果为空或不存在,请在此处提供var_dump($_POST) 的结果。
  • 坦克,我确实努力阅读$_POST['imgBase64']

标签: php ajax html canvas


【解决方案1】:

您应该从$_POST['imgBase64'] 变量中读取数据。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-22
    相关资源
    最近更新 更多