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);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 Revit2020下载问题
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 单片机无法进入HAL_TIM_PWM_PulseFinishedCallback回调函数
  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch