0

我已经能够使用 .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->Js->submit('Save'); 是否有我可以传递给提交函数的参数来保存图像数据?有没有更好的办法?

4

1 回答 1

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);
    }
  });
} 
于 2012-05-20T12:25:51.410 回答