douli7841 2013-05-04 11:40
浏览 79
已采纳

上传画布图像数据会产生空白图像

I'm using an ajax query to upload canvas image data, along with a few other variables. Here's what the relevant code looks like on the client side:

front_content = document.getElementById("front_paint_canvas").toDataURL("image/png");

ajaxHandler.open("POST", "upload_card", true);
ajaxHandler.setRequestHeader("Content-type","application/x-www-form-urlencoded");
ajaxHandler.send("name="+name+"&front_content="+front_content);

And here's what I have on the server side:

$front_content = substr($_POST['front_content'], strpos($_POST['front_content'], ",")+1);

$decodedData=base64_decode($front_content);

$fp = fopen( getcwd().'/assets/img/canvas.png', 'wb' );
fwrite( $fp, $decodedData);
fclose( $fp );

This creates a file that appears to be the right size, and is also of the right dimensions. However, the file is blank. None of the image data that was in the canvas shows up. What's being done wrong here?

  • 写回答

1条回答 默认 最新

  • doupo5861 2013-05-04 14:33
    关注

    When using jQuery.post() see: http://api.jquery.com/jQuery.post/ the ""application/x-www-form-urlencoded" content-type is not needed:

    javascript:

      // save canvas image as data url (png format by default)
      var dataURL = canvas.toDataURL();
      $.post("canvasdata.php", { data: dataURL } );
    

    php:

    //see: How to save a html5 Canvas.toDataURl string as a png on a php backend string-as-a-png-on-a-php-backend

     file_put_contents('test.png', base64_decode(substr($_POST['data'], strpos($_POST['data'], ",")+1)));
    

    update If you don't use jquery use this:

      // save canvas image as data url (png format by default)
      var dataURL = canvas.toDataURL();
      //$.post("canvasdata.php", { data: dataURL } );
    
      var ajaxHandler = new XMLHttpRequest();
      ajaxHandler.open("POST", "canvasdata.php", true);
      //ajaxHandler.setRequestHeader("Content-type","application/x-www-form-urlencoded");
      //ajaxHandler.send("name=test&data="+dataURL);
      var formData = new FormData();
      formData.append("name", "test");
      formData.append("data", dataURL);
      ajaxHandler.send(formData);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog