【问题标题】:upload image and store it into my database上传图像并将其存储到我的数据库中
【发布时间】:2019-05-11 11:05:06
【问题描述】:

我正在尝试创建表单以上传图像并将其存储到我的数据库中 但我遇到了这些问题: 注意:未定义索引:fileToUpload in

C:\xampp\htdocs\confee\admin\upload.php on line 3

Notice: Undefined index: fileToUpload in C:\xampp\htdocs\confee\admin\upload.php on line 8

Warning: getimagesize(): Filename cannot be empty in C:\xampp\htdocs\confee\admin\upload.php on line 8
File is not an image.Sorry, file already exists.
Notice: Undefined index: fileToUpload in C:\xampp\htdocs\confee\admin\upload.php on line 23
Sorry, only JPG, JPEG, PNG & GIF files are allowed.Sorry, your file was not uploaded.

这是我用来创建表单的代码


<form action="upload.php" method="post" enctype="multipart/form-data">
    Select Image File to Upload:
    <input type="file" name="file">
    <input type="submit" name="submit" value="Upload">
</form>

这是upload.php文件

<?php
// Include the database configuration file
include 'connect.php';
$statusMsg = '';

// File upload path
$targetDir = "uploads/";
$fileName = basename($_FILES["file"]["name"]);
$targetFilePath = $targetDir.$fileName;
$fileType = pathinfo($targetFilePath,PATHINFO_EXTENSION);

if(isset($_POST["submit"]) && !empty($_FILES["file"]["name"])){
    // Allow certain file formats
    $allowTypes = array('jpg','png','jpeg','gif','pdf');
    if(in_array($fileType, $allowTypes)){
        // Upload file to server
        if(move_uploaded_file($_FILES["file"]["name"], $targetFilePath)){
            // Insert image file name into database
            $insert = $db->query("INSERT into images (file_name, uploaded_on) VALUES ('".$fileName."', NOW())");
            if($insert){
                $statusMsg = "The file ".$fileName. " has been uploaded successfully.";
            }else{
                $statusMsg = "File upload failed, please try again.";
            } 
        }else{
            $statusMsg = "Sorry, there was an error uploading your file.";
        }
    }else{
        $statusMsg = 'Sorry, only JPG, JPEG, PNG, GIF, & PDF files are allowed to upload.';
    }
}else{
    $statusMsg = 'Please select a file to upload.';
}

// Display status message
echo $statusMsg;
?>

我真的陷入了这个问题,希望有人帮助我

【问题讨论】:

  • 警告:您对SQL Injections 持开放态度,应该真正使用参数化的prepared statements,而不是手动构建查询。它们由PDOMySQLi 提供。永远不要相信任何类型的输入,尤其是来自客户端的输入。即使您的查询仅由受信任的用户执行,you are still in risk of corrupting your data

标签: php html mysql sql database


【解决方案1】:

代码应该可以正常工作。 在按下上传按钮之前选择要上传的图像文件。 如果不是,它将显示上述错误。 谢谢。

【讨论】:

  • 你能详细说明一下吗?例如,您是否真的尝试过 andres 的代码并且它在您的环境中工作?如果是这样,您能否提供有关您的环境的一些详细信息(例如版本等)。我可能会冒险,因为我要做出一个假设,但安德烈斯可能确实选择了一个文件。
  • 是的。我确实在我的环境中尝试过,如果您先浏览图像文件然后按上传按钮,它应该可以正常运行。
猜你喜欢
  • 2016-10-12
  • 1970-01-01
  • 2019-10-18
  • 2011-12-15
  • 1970-01-01
  • 2013-04-19
  • 1970-01-01
  • 2017-10-19
  • 2020-10-31
相关资源
最近更新 更多