doumu1951
2014-05-07 20:51
浏览 56
已采纳

使用dataURL发送变量

Hi I have this code that works sending a dataURL to php and saving it to the server.

JS:

function addFormText(){
$('body').append('<input type="hidden" name="img_val" id="img_val" value="" />');
}

function capture() {
$('.Canvas').html2canvas({
    onrendered: function (canvas) {
        //Set hidden field's value to image data (base-64 string)
        $('#img_val').val(canvas.toDataURL("image/png"));
        var myImage = $('#img_val').val();


        $.ajax({

            type:"POST",
            url: "php/save.php",
            data: $('#img_val').val(canvas.toDataURL("image/png")),
            success: function(){
            }
        });
    }
});
}

PHP

//Show the image
echo '<img src="'.$_POST['img_val'].'" />';

//Get the base-64 string from data
$filteredData=substr($_POST['img_val'], strpos($_POST['img_val'], ",")+1);

//Decode the string
$unencodedData=base64_decode($filteredData);

//Save the image
file_put_contents('img.png', $unencodedData);
?>

What I'm having a problem with is sending another variable. When I try to do this the variable is uploaded but the dataURL is somehow broken the file is saved but is now 0B

JS:

            type:"POST",
            url: "php/save.php",
            data: $('#img_val').val(canvas.toDataURL("image/png"))+"&random="+random,
            success: function(){

PHP

<?php
//save.php code

$random = $_REQUEST['random'];

//Show the image
echo '<img src="'.$_POST['img_val'].'" />';

//Get the base-64 string from data
$filteredData=substr($_POST['img_val'], strpos($_POST['img_val'], ",")+1);

//Decode the string
$unencodedData=base64_decode($filteredData);

//Save the image
file_put_contents($random.'img.png', $unencodedData);
?>

Does anybody know why?

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • du970294 2014-05-07 20:57
    已采纳

    Try this:

            type:"POST",
            url: "php/save.php",
            data: {
                img_val: canvas.toDataURL("image/png"),
                random: random
            },
            success: function(){
    

    $_POST contains img_val and random keys

    已采纳该答案
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题