PHP和图像上传,在同一页面上显示服务器端错误

时间:2015-04-05 14:49:35

标签: php ajax file-upload

我有一个表单,它使用uploads.php。见下文:

<?php
    include 'config/database.php';

    $target_dir = "uploads/";
    $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
    $uploadOk = 1;
    $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);

    // Check if file already exists
    if (file_exists($target_file)) {
        echo "Sorry, file already exists.";
        $uploadOk = 0;
    }
    // Check file size
    if ($_FILES["fileToUpload"]["size"] > 500000) {
        echo "Sorry, your file is too large.";
        $uploadOk = 0;
    }
    // Allow certain file formats
    if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" && $imageFileType != "pdf" && $imageFileType != "doc" && $imageFileType != "docx") {
        echo "Sorry, only JPG, JPEG, PNG, DOC, PDF & GIF files are allowed.";
        $uploadOk = 0;
    }
    // Check if $uploadOk is set to 0 by an error
    if ($uploadOk == 0) {
        echo "Sorry, your file was not uploaded.";
    // if everything is ok, try to upload file
    } else {
        if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
            echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
        } else {
            echo "Sorry, there was an error uploading your file.";
        }
    }

    header("Location: http://same-page-the-form-is-on.php");

 ?>

表单(index.php):

<form id="myForm" action="uploads.php" method="post" enctype="multipart/form-data">
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" id="simple-post" value="Upload File Here" name="submit">
</form>


<?php
            $dir = "uploads/";
            $files = array_diff(scandir($dir), array('..', '.'));
            echo "<select>";
            foreach($files as $item ) {
                echo "<option value='.$item.'>" . $item . "</option>\n";
            }
            echo "</select>";
        ?>

因此,基于上传时发生的情况,无论是已存在的文件,文件太大还是文件扩展名错误,我希望在index.php上显示服务器端错误消息 。怎样才能解决这个问题? AJAX?

1 个答案:

答案 0 :(得分:0)

您可以调用一个从Index.php执行服务器端验证的函数,并将该函数的抛出错误返回到该Index.php并将其回显。如果设置了某个POST变量,则可以启动该函数。