Base64图像通过Ajax encodeURIComponent发送
问题描述:
我想通过ajax发送base64转换图像到PHP后端。我使用encodeURIComponent来编码base64图像,还必须使用encodeURI来编码参数。否则,它不断给我403拒绝访问错误。当我发送像这样的形象变得腐败的形象。当我只使用encodeURIComponent来编码图像。和发送,而不使用是encodeURI它完美编码参数。(仅在本地服务器。)Base64图像通过Ajax encodeURIComponent发送
下面的代码只能在本地服务器(WAMP)的作品
var img = canvas.toDataURL("image/png");
var Parameters = "image=" + encodeURIComponent(img) + "&filename=" + name;
$.ajax({
type: "POST",
url: "savePNG.php",
data: Parameters,
success: function (response) {
alert(response);
}
});
当我再次它编码data: encodeURI(Parameters),
将数据解析到后端。但图像会变坏(我认为是因为它编码了两次)。
PHP后端代码如下所示。
$image = $_POST['image'];
$filename = $_POST['filename'];
$image = str_replace('data:image/png;base64,', '', $image);
$decoded = base64_decode($image);
file_put_contents($filename . ".png", $decoded, LOCK_EX);
echo $image;
有没有办法在服务器上工作,没有图像变坏。
答
使用以下技巧。
的JavaScript
var img = canvas.toDataURL("image/png");
var ajax = new XMLHttpRequest();
ajax.open("POST", 'savePNG.php', false);
ajax.setRequestHeader('Content-Type', 'application/upload');
ajax.send(img);
PHP代码
$imageData=$GLOBALS['HTTP_RAW_POST_DATA'];
$filteredData=substr($imageData, strpos($imageData, ",")+1);
$unencodedData=base64_decode($filteredData);
$fp = fopen("filename.png", 'wb');
fwrite($fp, $unencodedData);
fclose($fp);
谢谢你的男人。你的代码帮助我解决了我的问题。 – Rajkeshar