duanjuelian4640 2017-05-19 19:24
浏览 71
已采纳

Canvas不会保存服务器端PHP

I have a canvas which I need to save to a directory and store the URL in a database.

When I save the file without storing the URL in the database it works fine, and vice versa.

However, when I put the two together and specify the PHP file through AJAX, for some reason it doesn't recognise the session variable?

When I try to call the "success" on AJAX, nothing shows up. I get no response.

This could possibly be an easy fix! I think I've been staring at this code for too long.

JavaScript:

function doodleSave() {
  var canvas = document.getElementById("doodle-canvas");
  var canvasData = canvas.toDataURL("image/png");

  $.ajax({
    url:'doodleupload.php', 
    type:'POST', 
    data:{ data:canvasData },
    success: function(response){
        alert(response);
        //echo what the server sent back...
    }
  });
}

PHP:

<?php
  session_start();

  /* AUTOMATED VARIABLES */
  $url             = md5(uniqid(rand(), true));
  $unique_user_id  = $_SESSION['unique_user_id'];
  $unique_post_id  = md5(uniqid(rand(), true));
  $timestamp       = time();
  $nature          = "doodle";
  $imageUrl        = $upload_dir.$url.'.png';

  $upload_dir = "images/external/doodles/";
  $img = $_POST['data'];
  $img = substr($img,strpos($img,",")+1);
  $data = base64_decode($img);
  $file = $upload_dir . $url . ".png";
  $success = file_put_contents($file, $data);

  echo $success ? $file : 'Unable to save the file.';

  require_once 'php/connect.php';

  try
  {

    $stmt = $pdo->prepare("INSERT INTO posts (unique_user_id, unique_post_id, nature, image_url, timestamp) VALUE (:unique_user_id, :unique_post_id, :nature, :image_url, :timestamp)");
    $stmt->bindParam(":unique_user_id",$unique_user_id);
    $stmt->bindParam(":unique_post_id",$unique_post_id);
    $stmt->bindParam(":nature",$nature);
    $stmt->bindParam(":image_url",$imageUrl);
    $stmt->bindParam(":timestamp",$timestamp);

    if($stmt->execute())
    {
      echo "File in database";
    }
    else
    {
      echo "Not in database";
    }
  }
  catch(PDOException $e){
    echo $e->getMessage();
  }

?>
  • 写回答

1条回答 默认 最新

  • dongyi0114 2017-05-19 20:36
    关注

    Move $upload_dir at the top, as you are calling it before you initialize it.

    $upload_dir = "images/external/doodles/";
    $url             = md5(uniqid(rand(), true));
    $unique_user_id  = $_SESSION['unique_user_id'];
    $unique_post_id  = md5(uniqid(rand(), true));
    $timestamp       = time();
    $nature          = "doodle";
    $imageUrl        = $upload_dir.$url.'.png';
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题
  • ¥15 FPGA-SRIO初始化失败
  • ¥15 MapReduce实现倒排索引失败
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码
  • ¥50 随机森林与房贷信用风险模型