使用dataURL发送变量

时间:2014-05-07 20:51:23

标签: javascript php

您好我有这个代码可以将dataURL发送到php并将其保存到服务器。

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);
?>

我遇到的问题是发送另一个变量。当我尝试这样做时,变量被上传但是dataURL以某种方式被破坏了文件被保存但现在是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);
?>

有人知道为什么吗?

1 个答案:

答案 0 :(得分:1)

试试这个:

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

$_POST包含img_valrandom个密钥