我已经能够使用.ajax()和php保存画布图像数据,但不能保存。我这样做的方式如下。我有一个javascript,当用户在制作画布后点击表单中的“提交”按钮时运行:
var formdata = $("form").serialize();
var data = document.getElementById("canvasElement").toDataURL();
formdata += "&img=" + data;
$.ajax({
type: "POST",
url: "process.php",
data: formdata,
success: function() {
$('body').prepend('<div class="alert">Your bit of data was successfully saved.</div');
$('.alert').delay(2000).slideUp('slow');
},
error:function (xhr, ajaxOptions, thrownError){
alert("Error Status: " + xhr.status + " Thrown Errors: "+thrownError);
}
然后process.php处理图像数据并将其保存到文件中。这是最重要的部分:
$img = $_POST['img'];
// remove header information that's sent with the encoded data
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = "images/" . uniqid() . '.png';
这一切都像我希望的那样有效。我怎么能在cakephp框架中做到这一点?我已经读过,代替常规蛋糕表单提交,你可以使用Js助手进行ajax提交,如下所示: echo $ this-&gt; Js-&gt; submit('Save'); 有没有我可以传递给提交函数的参数,可以让我保存图像数据?有没有更好的办法?
答案 0 :(得分:0)
我已经开始工作,但我不完全确定我理解为什么,我想了解在蛋糕中做到这一点的最好方法。我为Js助手添加了一个命令,将脚本放在头部:echo $this->Js->writeBuffer(array('cache'=>TRUE));
除此之外,我认为我没有改变任何东西。但是,我在控制器中的保存功能中的重定向没有做任何事情。我只能通过将它放在如下的javascript中来实现重定向。
<?php
// This is my form for saving the drawing
echo $this->Form->create('Drawing');
echo $this->Js->submit('Save', array(
'before'=>$this->Js->get('#sending')->effect('fadeIn')
));
echo $this->Form->end();
?>
public function save() {
// This is my save function in the controller
if ($this->request->is('post')) {
$img = $this->request->data['img'];
// remove header information that's sent with the encoded data
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = uniqid() . '.png';
$filepath = 'drawings/';
$success = file_put_contents($filepath . $file, $data);
print $success ? $file : 'Unable to save the file.';
$arr = array( 'Drawing' => array ( 'filename' => $file, 'filepath' => '/images'));
if ($this->Drawing->save($arr)) {
$this->Session->setFlash('Your drawing has been saved!');
// this redirect doesn't work (and I do have an index page and function)
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash('Unable to add your post.');
}
}
}
Javascript在这里:
var data = document.getElementById("canvasElement").toDataURL();
formdata = "img=" + data;
$.ajax({
type: "POST",
url: "save",
data: formdata,
success: function() {
window.location.replace("index"); // This redirect works
},
error:function (xhr, ajaxOptions, thrownError){
alert('error in: ' + settings.url + ' \\n'+'error:\\n' + exception);
}
});
}