Jquery Ajax保存画布图像已损坏(解码错误?)
我正在尝试获取画布数据并将其保存为png文件。我正在使用下面的ajax代码,并不断获得保存的图像,但图像已损坏。也许我有错误的$请求属性 感谢您的帮助Jquery Ajax保存画布图像已损坏(解码错误?),jquery,ajax,Jquery,Ajax,我正在尝试获取画布数据并将其保存为png文件。我正在使用下面的ajax代码,并不断获得保存的图像,但图像已损坏。也许我有错误的$请求属性 感谢您的帮助 var dataURL = canvas.toDataURL('image/png'); var imageURL; $.ajax({ url: "saveimage.php", type: 'POST', dataType: 'json',
var dataURL = canvas.toDataURL('image/png');
var imageURL;
$.ajax({
url: "saveimage.php",
type: 'POST',
dataType: 'json',
data: { 'data_url': dataURL },
complete: function(xhr, textStatus) {
// Request complete.
},
// Request was successful.
success: function(response, textStatus, xhr) {
console.log('Response: ', response);
// Conversion successful.
if (response.status_code === 200) {
imageURL = response.data.image_url;
// Paste the PNG image url into the input field.
document.querySelector('img').src = imageURL;
}
},
error: function(xhr, textStatus, errorThrown) {
// Some error occured.
console.log('Error: ', errorThrown);
}
});
}
<?php
file_put_contents('images/'. rand().'.png', base64_decode($_REQUEST['data_url']));
?>
var-dataURL=canvas.toDataURL('image/png');
var-imageURL;
$.ajax({
url:“saveimage.php”,
键入:“POST”,
数据类型:“json”,
数据:{'data_url':dataURL},
完成:功能(xhr、textStatus){
//请求完成。
},
//请求成功。
成功:函数(响应、文本状态、xhr){
log('Response:',Response);
//转换成功。
如果(response.status_code==200){
imageURL=response.data.image\u url;
//将PNG图像url粘贴到输入字段中。
document.querySelector('img').src=imageURL;
}
},
错误:函数(xhr、textStatus、errorshown){
//发生了一些错误。
log('Error:',errorshown);
}
});
}
事实证明,这样做的方法是将数据分解开来,因为datatoURL实际上包含的信息比我们需要的更多。这段代码对我很有用,希望它也能帮助其他人:
<?php
$data = $_REQUEST['data_url'];
list($t, $data) = explode(';', $data);
list(, $data) = explode(',', $data);
$data = base64_decode($data);
$filename='images/'. rand().'.png';
file_put_contents($filename, $data);
$response = array("image_url"=>$filename,"status_code"=>200);
echo json_encode($response);
?>