您好我有这个代码可以将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);
?>
有人知道为什么吗?
答案 0 :(得分:1)
试试这个:
type:"POST",
url: "php/save.php",
data: {
img_val: canvas.toDataURL("image/png"),
random: random
},
success: function(){
$_POST
包含img_val
和random
个密钥