将Javascript变量作为图像传递给PHP

时间:2017-11-03 16:59:43

标签: javascript php image

我在这里找到了一个很酷的github项目,用于网页签名https://github.com/szimek/signature_pad

示例代码将签名保存为图像并下载,代码如下。我需要将图像传回我的PHP脚本,以便将其保存在服务器上。任何帮助将不胜感激。

savePNGButton.addEventListener("click", function (event) {
  if (signaturePad.isEmpty()) {
    alert("Please provide a signature first.");
  } else {
    var dataURL = signaturePad.toDataURL();
    download(dataURL, "signature.png");
  }
});

2 个答案:

答案 0 :(得分:0)

对于我能看到的内容,您可以使用

// JS Returns signature image as an array of point groups
var imgData = signaturePad.toData();

将签名本地存储在JS变量上作为base64编码,然后使用AJAX

将其发送到服务器
$.ajax({
    type: "POST",
    url: "index.php?action=saveSomeImage",
    data: {img: encodeURIComponent(imgData)},
    contentType: "application/x-www-form-urlencoded;charset=UTF-8",
    success: function(){
        //...
    }
});

然后,在PHP端将其写入磁盘

file_put_contents('foo.png', base64_decode( urldecode($_POST['img'])));

答案 1 :(得分:0)

基本上你需要将它以JSON传递给PHP。像这样的东西应该做的工作(我使用jQuery):

savePNGButton.addEventListener("click", function (event) {
  if (signaturePad.isEmpty()) {
    alert("Please provide a signature first.");
  } else {
    var dataURL = signaturePad.toDataURL();
    obj={};
    obj["signature"] = dataURL;

 var data=JSON.stringify(obj);

    $.ajax({
        url: 'yourphp.php',
        type: 'POST',
        data: data,
        contentType: 'application/json; charset=utf-8',
        success: function(msg) {
//do something on success
            console.log(msg)

        },error: function(msg) {
//do something on error
            console.log(msg)
        }

  }
});