[英]PHP: upload a canvas image to server and save image directory to database
i am new in PHP and web development in general. 我是一般PHP和Web开发的新手。 I want to upload an image from an HTML canvas to server and save its location to my database, but for some reason that i could not point, it fails to do so.
我想将图像从HTML画布上载到服务器,并将其位置保存到我的数据库中,但是由于某种原因,我无法指向该对象,因此无法这样做。 Uploading the image to server works just fine, but i am having a problem with saving its location.
将图像上传到服务器工作正常,但是我在保存其位置时遇到问题。
My code: 我的代码:
//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 Code: 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();
?>
Is there something wrong with my code that i fail to see? 我的代码有什么不对的地方吗? Thanks in advance!
提前致谢!
Make sure you have the permission of the upload directory. 确保您具有上载目录的权限。
(Linux: chmod -R 777 /path/to/upload)
(Linux:chmod -R 777 / path / to / upload)
I am sorry, i am really embarrassed. 对不起,我真的很尴尬。 Turns out, my code was working perfectly fine.
事实证明,我的代码运行得很好。 I just forgot to turn to the last page of my database, the newly inserted records was there all those time!
我只是忘了转到数据库的最后一页,这些时间里一直在插入新插入的记录!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.