2012-05-20 47 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); 
    } 
    }); 
}