照片上传到服务器和数据库的问题

问题描述 投票:0回答:1

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

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

我想知道我的插入是否可能存在问题,因为我正在尝试插入文件名,但随后也通过执行'images /'加上文件名来删除网址。所有图像都要上传到ima​​ges目录中,所以我想确保URL的前面总是有'images /'。

我不确定这里还有什么可能出错但也许我错过了什么

这是表单和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;
php html mysql upload
1个回答
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"

© www.soinside.com 2019 - 2024. All rights reserved.