Javascript dataURL POST到PHP不起作用

我正在尝试将 dataURL 发布到 php 但没有成功。我的 .js 文件如下。


var dataURL = signaturePad.toDataURL();

alert(dataURL);

$.ajax({ 

    type: "POST", 

    url: "test.php", 

    data: { 

    imgBase64: dataURL 

    } 

    }).done(function(o) { 

      console.log('saved');

      alert(o); 

    });

alert(dataURL) 输出如下;


data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAhkAAADZCAYAAACNbSIWAAAeW.....

测试.php


<?php

if($_POST['imgBase64']) { 

$img = $_POST['imgBase64'];

}

else{

$img = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAhkAAADZCAYAAACNbSIWAAAeW.....";

}

$img = str_replace('data:image/png;base64,', '', $img);

$img = str_replace(' ', '+', $img);

$fileData = base64_decode($img);

//saving

$timestamp = date('YmdHis');

$fileName = ''.$timestamp.'.png';

echo"$fileData";

file_put_contents($fileName, $fileData);

?>

在我的 php 文件中,我输入了警报的值以进行测试。现在我的 php 页面由于测试而 100% 工作并且没有从我的 .js 函数传递任何值。但是使用正确的值,它甚至不会发布到我的 php 页面,只有当我从 dataURL 中删除所有非标准字符时,它才会发布,但数据损坏很明显。


为避免进一步混淆,以下代码 .js 和 php 100% 有效。其中 var dataURL = signaturePad.toDataURL(); 传递给函数


function postData(data) {

    alert(data);

    var desired = data.replace(/[^\w\s]/gi, '');

    $.ajax({ 

        type: "POST", 

        url: "test.php", 

        data: { 

        imgBase64: desired 

        } 

    }).done(function(o) { 

       console.log('saved');

       alert(o); 

    }); 

}

所以问题是由于特殊字符,.js 不会使用给定的 dataUrl 发布,但我无法删除它们。我什至尝试过 var desired = encodeURIComponent(data); 女巫我至少可以在 php 页面上解码,但这也不想发布。


慕丝7291255
浏览 114回答 2
2回答

慕神8447489

谢谢大家的回复。。我最终首先创建了一个 blob 并发布了 blob。function dataURLToBlob(dataURL) {&nbsp; var parts = dataURL.split(';base64,');&nbsp; var contentType = parts[0].split(":")[1];&nbsp; var raw = window.atob(parts[1]);&nbsp; var rawLength = raw.length;&nbsp; var uInt8Array = new Uint8Array(rawLength);&nbsp; for (var i = 0; i < rawLength; ++i) {&nbsp; &nbsp; uInt8Array[i] = raw.charCodeAt(i);&nbsp; }&nbsp; return new Blob([uInt8Array], { type: contentType });&nbsp;&nbsp; &nbsp; $.post("test2.php",&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; name: uInt8Array&nbsp; &nbsp; },&nbsp; &nbsp; function(data,status){&nbsp; &nbsp; &nbsp; alert("Data: " + data + "\nStatus: " + status);&nbsp; &nbsp; });}

MM们

data: {&nbsp;&nbsp; &nbsp; imgBase64: data&nbsp; &nbsp; //send key is imgBase64 and data value is undefined in given scope&nbsp; &nbsp; //replace data with dataURL}&nbsp;并在 php 文件中将其更改$_POST['image']为$_POST['imgBase64']
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript