将照片上传到服务器和数据库时出现问题

时间:2018-09-17 02:42:02

标签: php html mysql upload

在我的网站上上传照片时遇到问题。

我在$fileName = basename($_FILES["file"]["name"]);行收到最后一条错误消息(“请选择要上传的文件”),并且没有插入到数据库或在服务器上上传。

我想知道插入是否有问题,因为我要插入文件名,然后通过执行'images /'和文件名来插入url。所有图像都将上传到图像目录中,因此我想确保URL始终始终在其前面。'

我不确定这里还有什么问题,但也许我遗漏了一些东西

这是表格和php脚本:

<form action="uploadImage.php" method="post" enctype="multipart/form-data">
  <div class="form-group">
    <label for="formControl">Upload Image</label>
    <input type="file" class="form-control-file" id="formControl">
    <input type="submit" name="fileUpload">
  </div>
</form>

$statusMsg = '';

// File upload path
$targetDir = "images/";
$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"]["tmp_name"], $targetFilePath)){
            // Insert image file name into database
            $insert = $mysqlConn->query("INSERT into images (image_name, url) VALUES ('".$fileName."', 'images/".$fileName."'");
            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 :(得分:1)

根据您的验证,您应该像这样修改html标记:

<input type="file" name="file" class="form-control-file" id="formControl">
<input type="submit" name="submit">

或将您的验证条件更改为

if (isset($_POST["fileUpload"]) && !empty($_FILES["file"]["name"])) {
   ...
}

无论如何,文件输入元素需要name="file"