PHP:将画布图像上传到服务器并将图像目录保存到数据库

时间:2018-05-15 01:59:20

标签: javascript php

我是PHP和Web开发的新手。我想将一个图像从HTML画布上传到服务器并将其位置保存到我的数据库,但由于某些原因我无法指出,它无法这样做。将图像上传到服务器工作正常,但我在保存位置时遇到问题。

我的代码:

    //javascript to pass canvas data to php
    <script>
        function uploadEx() {
            var canvas = document.getElementById("canvas");
            var dataURL = canvas.toDataURL("image/png");
            document.getElementById('hidden_data').value = dataURL;
            var fd = new FormData(document.forms["form1"]);

            var xhr = new XMLHttpRequest();
            xhr.open('POST', 'upload_data.php', true);

            xhr.upload.onprogress = function(e) {
                if (e.lengthComputable) {
                    var percentComplete = (e.loaded / e.total) * 100;
                    console.log(percentComplete + '% uploaded');
                    alert('Succesfully uploaded');
                }
            };

            xhr.onload = function() {

            };
            xhr.send(fd);
        };
    </script>

PHP代码:

<?php
//upload image to server
$upload_dir = "upload/";
$img = $_POST['hidden_data'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = $upload_dir . mktime() . ".png";
$success = file_put_contents($file, $data);
print $success ? $file : 'Unable to save the file.';
echo "" . $file

//save the location to database
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "signatures";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
$escapedString = mysqli_real_escape_string($conn,$file);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} 

$sql = "INSERT INTO signatures (imagePath)
VALUES ('".$escapedString."')";

if ($conn->query($sql) === TRUE) {
  echo "New record created successfully";
} else {
  echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
?>

我的代码有什么问题我看不到吗?提前谢谢!

2 个答案:

答案 0 :(得分:0)

确保您拥有上传目录的权限。

  

(Linux:chmod -R 777 / path / to / upload)

答案 1 :(得分:0)

对不起,我真的很尴尬。事实证明,我的代码工作得非常好。我只是忘了转到我的数据库的最后一页,新插入的记录就在那里!