上传图片时如何防止空表单提交?

时间:2014-02-24 16:15:32

标签: php mysql image forms submit

我有一个上传图片的脚本(是的,我知道它是在折旧的mysql中)。如何在用户上传图像之前阻止提交表单?我尝试过使用if(空)但不明白如何使它适用于图像。

(我使用javascript来设置上传按钮的样式)

<?php
session_start();
include "connect.php";
//require("checkLoginSession.php");
$message = $_GET['message'];
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
$path = "uploads/" . $_FILES["file"]["name"];
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/png"))
&& ($_FILES["file"]["size"] < 2000000)
&& in_array($extension, $allowedExts))
  {
  if ($_FILES["file"]["error"] > 0)
    {
    echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
    }
  else
    {
    echo "Upload: " . $_FILES["file"]["name"] . "<br>";
    echo "Type: " . $_FILES["file"]["type"] . "<br>";
    echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
    echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";
    echo '<img src="'.$path.'" alt="" />';

    if (file_exists("uploads/" . $_FILES["file"]["name"]))
      {
      echo $_FILES["file"]["name"] . " already exists. ";
      }
    else
      {
      move_uploaded_file($_FILES["file"]["tmp_name"],
      "uploads/" . $_FILES["file"]["name"]);
      echo "Stored in: " . "uploads/" . $_FILES["file"]["name"];
      }
    }
}

$Link = mysql_connect($Host, $User, $Password);
$user = $_SESSION['UserName'];
$Query = "INSERT INTO $Table_3 VALUES ('0','".mysql_escape_string($user)."','{$path}')";
?>

<form action="upload_file.php?CreateRecord=1" method="post" enctype="multipart/form-data" name="form1" id="genericForm">
<div class="uploadimgbtn" onclick="getFile()"><p class="upload">Upload Image</p></div>
<div style='height: 0px;width: 0px; overflow:hidden;'><input id="upfile" type="file" name="file" onchange="sub(this)"/></div>
<input type="submit" value='submit' >
</form>

1 个答案:

答案 0 :(得分:0)

试试这个:

<script type="text/javascript">
function check(){
    var file = document.getElementById('upfile');
    if(file.value === null || file.value === ""){
        alert('THERE'S NO FILE');
        return false;
    }
    else{
        alert('FILE IS UPLOADED');
        return true;
    }
    }

</script>

然后,您只需在提交按钮上调用该功能。

<input type="submit" value='submit' onclick='return check();'>

希望这可以帮到你。