2012-05-20 46 views
0

我已经能够使用.ajax()和php保存画布图像数据,但不能保存在蛋糕中。我做过的方式如下所示。我有一个运行,当用户点击一个JavaScript的形式“提交”按钮制作画布绘制后:如何在cakephp中保存HTML5画布图像?

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 helper来提交一个像这样的AJAX提交: echo $ this-> Js-> submit('Save'); 是否有参数可以传递给提交函数,让我保存图像数据?有没有更好的办法?

回答

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); 
    } 
    }); 
}