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 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀