上传图片并将其存储到我的数据库中

时间:2019-05-11 11:05:07

标签: php html mysql sql database

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

中的fileToUpload
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;
?>

我真的陷在这个问题中,希望有人帮助我

1 个答案:

答案 0 :(得分:0)

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