为什么这段代码不能将图像存储到我的数据库中?

huangapple go评论57阅读模式
英文:

Why does this Code to store an Image in my database not work?

问题

我花了好几个小时来尝试将图像存储在我的数据库中,但我一直搞不定。目前,我正尝试通过用户上传文件来获取图像,然后将其存储为BLOB类型在数据库中。实际上,就是将图像的二进制数据存储在数据库中。

这是我的表单,我知道结构混乱,但这并不重要。

当你点击按钮时,应该执行以下代码:

这个代码似乎不起作用,因为它从不执行,因为我在表单中写了action="editor.php"。但这不是问题所在。

问题是PHP无法获取我的文件以进行上传。在这里:

ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);
session_start();
include 'dbconnect.php';

$content = $_POST['content'];
$title = $_POST['title'];
$category = $_POST['category'];

date_default_timezone_set('Europe/Rome');
$date = date("YmdHis"); 

$status = 'error'; 
if(!empty($_FILES["image"]["name"])) { 
    // 获取文件信息 
    $fileName = basename($_FILES["image"]["name"]); 
    $fileType = pathinfo($fileName, PATHINFO_EXTENSION); 

    // 允许特定文件格式 
    $allowTypes = array('jpg','png','jpeg','gif'); 
    if(in_array($fileType, $allowTypes)){ 
        $image = $_FILES['image']['tmp_name']; 
        $imgContent = addslashes(file_get_contents($image));

        // 将图像内容插入数据库 
        $insert = $db->query("INSERT INTO `blog_posts`(`coverImage`) VALUES ('$imgContent');");
         
        if($insert){ 
            $status = 'success'; 
            $statusMsg = "文件上传成功。"; 
        }else{ 
            $statusMsg = "文件上传失败,请重试。"; 
        }  
    }else{ 
        $statusMsg = '抱歉,只允许上传JPG、JPEG、PNG和GIF文件。'; 
    } 
}else{ 
    $statusMsg = '请选择要上传的图像文件。'; 
} 

// 显示状态消息 
echo $statusMsg;

$sql = "INSERT INTO `blog_posts`(`created_at`, `last_updated_at`, `content`, `title`, `category`) 
VALUES('$date', '$date', '$content', '$title', '$category');";
$execution = mysqli_query($conn, $sql) or die("错误");
?>

为了测试,你可以为这些行提供一个值,以防出现错误。

但我仍然得到错误消息:"请选择要上传的图像文件。"我对PHP、JavaScript和Web开发都很陌生,所以请原谅我的混乱代码。

英文:

so I'm trying now for hours to store an Image in my Database, but I just don't get it. Currently I'm trying to get the image via file upload from the user, then store in the database as a BLOB. So practically storing the binary data of the image in the database.

<form action="editor.php" class="createBlogForm" autocomplete="off">
                    <input type="text" name="title" placeholder="Title" class="title">
                
                <?php include 'editor.html'; ?>
            </div>
            <div id="catAndSave">
                <select name="categoriesOnCreate" class="categoriesOnCreate">
                    <option value="option1">Option 1</option>
                    <option value="option2" selected="selected">Anderes</option>
                </select>
                <div id="coverImageDiv">
                    <label for="inputTag">
                        Select Cover Photo <br/>
                        <i class="fa fa-2x fa-camera"></i>
                        <input id="inputTag" type="file" name="image"/>
                        <br/>
                        <span id="imageName"></span>
                    </label>
                </div>
                  <script>
                    let input = document.getElementById("inputTag");
                    let imageName = document.getElementById("imageName")
            
                    input.addEventListener("change", ()=>{
                        let inputImage = document.querySelector("input[type=file]").files[0];
            
                        imageName.innerText = inputImage.name;
                    })
                </script>
                <button type="submit" class="blogSave" onclick="save();">Save</button>
                </form>

So this is my form, I know very unstructured and things, but it doesn't have to be.

When you click on the button this Code should be executed:

<script>
                function save(){
                    var xmlhttp = new XMLHttpRequest();
                    var content = document.getElementsByClassName('content')[0].innerHTML;
                    var title = document.getElementsByClassName('title')[0].value;
                    var category = document.getElementsByClassName('categoriesOnCreate')[0].value;
                    var data = new FormData();
                    data.append("content", content);
                    data.append("title", title);
                    data.append("category", category);
                    const queryString = window.location.search;
                    const urlParams = new URLSearchParams(queryString);
                    const id = urlParams.get('id');
                    xmlhttp.open("POST","editor.php?id=" + id ,true);
                    xmlhttp.send(data);
                    window.location = "http://192.168.56.104/sodablog/editor.php";
                };
            </script>

Doesn't quite work tho, because it never executes this, because i wrote in my form: action="editor.php". But that's not the point and doesn't matter, cause that's not the problem.

The problem is that PHP doesn't get my file to upload it. Here:

<?php
    ini_set('display_errors', '1');
    ini_set('display_startup_errors', '1');
    error_reporting(E_ALL);
    session_start();
    include 'dbconnect.php';

    $content = $_POST['content'];
    $title = $_POST['title'];
    $category = $_POST['category'];

    date_default_timezone_set('Europe/Rome');
    $date = date("YmdHis"); 

  
    $status = 'error'; 
    if(!empty($_FILES["image"]["name"])) { 
        // Get file info 
        $fileName = basename($_FILES["image"]["name"]); 
        $fileType = pathinfo($fileName, PATHINFO_EXTENSION); 
         
        // Allow certain file formats 
        $allowTypes = array('jpg','png','jpeg','gif'); 
        if(in_array($fileType, $allowTypes)){ 
            $image = $_FILES['image']['tmp_name']; 
            $imgContent = addslashes(file_get_contents($image));
         
            // Insert image content into database 
            $insert = $db->query("INSERT INTO `blog_posts`(`coverImage`) VALUES ('$imgContent');");
             
            if($insert){ 
                $status = 'success'; 
                $statusMsg = "File uploaded successfully."; 
            }else{ 
                $statusMsg = "File upload failed, please try again."; 
            }  
        }else{ 
            $statusMsg = 'Sorry, only JPG, JPEG, PNG, & GIF files are allowed to upload.'; 
        } 
    }else{ 
        $statusMsg = 'Please select an image file to upload.'; 
    } 

 
// Display status message 
echo $statusMsg;

    $sql = "INSERT INTO `blog_posts`(`created_at`, `last_updated_at`, `content`, `title`, `category`) 
    VALUES('$date', '$date', '$content', '$title', '$category');";
    $execution = mysqli_query($conn, $sql) or die("Fehler");
?>

For testing you could just here give these lines:

$content = $_POST['content'];
    $title = $_POST['title'];
    $category = $_POST['category'];

a value so no error appears because of these.

But I still get the error: Please select an image file to upload.

I'm new to PHP and JavaScript and Web-development in general, so sorry for the chaotic code.

答案1

得分: 1

你没有将图像从前端发送到后端。

    function save(){
    ...    
    var image = document.getElementById('inputTag').value;
    ...
    var data = new FormData();
    ...
    data.append(image.name,image.files[0]);
    ...
英文:

You are not sending your image from your frontend to your backend.

function save(){
...    
var image = document.getElementById('inputTag').value;
...
var data = new FormData();
...
data.append(image.name,image.files[0]);
...

huangapple
  • 本文由 发表于 2023年2月19日 18:05:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/75499333.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定