如何使用JavaScript发布包含文件类型参数的表单



我正在尝试使用JavaScript发布HTML表单,但我找不到如何以参数作为文件传递。如果我在不使用JavaScript的情况下发布表单,则一切正常。我的问题是我不知道如何将文件数组传递到JavaScript变量中。我尝试了不同的方法,但找不到正确的方法:

var fileToUpload1 = $("#fileToUpload2").val();
var fileToUpload1 = document.getElementById("fileToUpload2").files[0];
var fileToUpload1 = document.forms['imageform2']['fileToUpload2'].files[0];

我发布代码,以防它有所帮助。HTML表单和JavaScript都在同一文件中。上传代码位于名为upload.php的单独文件中。

html表格:

                <form id="imageform2" action="upload.php" method="post" enctype="multipart/form-data">
                    <p> Add new photo</p>
                    <p>Description :
                    <textarea id="description2" name= "description2" rows=6 cols=20 required></textarea></p>
                    Category :
                     <select id="category2" name="category">
                        <option value="0">Face</option>
                        <option value="1">Landscape</option>
                        <option value="2">Attraction</option>
                        <option value="3">Object</option>
                    </select>
                    <p>Select image:
                    <input id="fileToUpload2" type="file" name="fileToUpload2" required></p>
                    <input id="submit" type="button" value="Submit">
                    <input type="reset" value="Reset">
                </form> 

javaScript:

<script>
    $(document).ready(function() {
        $("#submit").click(function() {
            var description1 = $("#description2").val();
            var category1 = $("#category2").val();
            var fileToUpload1 = $("#fileToUpload2").val();
            alert(description1 + " " + category1 + " " + fileToUpload1);
            if (description1 == '' || category1 == '') 
            {
                if (description1 == '') alert("Insertion Failed description is Blank....!!");
                else if (category1 == '') alert("Insertion Failed category is Blank....!!");
                //else if (fileToUpload1 == '') alert("Insertion Failed fileToUpload is Blank....!!");
                else alert("Insertion Failed Some Fields are Blank....!!");
            } 
            else 
            {
                // Returns successful data submission message when the entered information is stored in database.
                $.post("upload.php", 
                {
                    description: description1,
                    category: category1,
                    fileToUpload: fileToUpload1
                }, function(data) {
                alert(data);
                });
            }
        });
    });
</script>

上传:

<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
session_start();
if(isset($_POST["submit"])) {
    $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
    if($check !== false) {
        echo "File is an image - " . $check["mime"] . ".";
        $uploadOk = 1;
    } else {
        echo "File is not an image.";
        $uploadOk = 0;
    }
}
// Check if file already exists
if (file_exists($target_file)) {
    echo "Sorry, file already exists.";
    $uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 2000000) {
    echo "Sorry, your file is too large.";
    $uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
    echo "Sorry, only JPG, JPEG, PNG & 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.";
        $_SESSION['uploaded']="true";
    } else {
        echo "Sorry, there was an error uploading your file.";
    }
}
?>

使用formdata提交包含文件输入的ajax的表单。

首先,让我们注意onsubmit事件在表格上发射,而不是按钮上的onclick事件。

为了使用formData,我们需要使用$ .ajax()而代替$ .post(),因为需要添加某些设置才能正常工作。FYI $ .post()是使用$ .ajax()用于发布请求的速记方式。如果您需要拥有更多的配置设置,就像我们现在一样,请使用$ .ajax()。

$(document).ready(function() {
    $("#imageform2").submit(function(e) {
        e.preventDefault();
        // simplified validation logic
        if ($("#description2").val() == '') {
            alert("Insertion Failed description is Blank....!!");
        } else if ($("#category2").val() == '') {
            alert("Insertion Failed category is Blank....!!");
        } else if ($("#fileToUpload2").val() == '') {
            alert("Insertion Failed fileToUpload is Blank....!!");
        } else {
            // send request 
            $.ajax({
                type: this.method,
                url: this.action,
                data: new FormData(this), // important
                processData: false, // important
                contentType: false, // important
                success: function (data) {
                    alert(data);
                }
            });
        }
    });
});

在服务器端上的接下来,让我们改进文件检查一点。在操纵它之前,您应该始终检查超级全局变量的存在。

让我们在trycatch中包装验证逻辑。如果某个点有错误,则毫无意义地进行验证是没有意义的。如果通过与适当消息的异常发生错误发生错误,我们将退出验证。

// just in case, let's turn on the errors
error_reporting(E_ALL);
ini_set('display_errors', 1);
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $file = isset($_FILES['fileToUpload2']['tmp_name']) ? $_FILES['fileToUpload2'] : null;
    // start validation
    try {
        // check if file was NOT provided
        if (!$file ||
            !file_exists($file['tmp_name']) || 
            !is_uploaded_file($file['tmp_name']) || 
            $file['error'] !== UPLOAD_ERR_OK) {
            throw new Exception('No file was given.');
        }
        // check if file is NOT an image
        $size = getimagesize($file['tmp_name']);
        if ($size === false) {
            throw new Exception('File is not an image.');
        }
        // check if file already exists
        $target_dir = 'uploads/';
        $target_file = $target_dir . basename($file['name']);
        if (file_exists($target_file)) {
            throw new Exception('File already exists.');
        }
        // check file size is too large
        if ($file['size'] > 2000000) {
            throw new Exception('File is too large.');
        }
        // check file extension is NOT accepted
        $extension = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
        if (!in_array($extension, ['jpg', 'png', 'gif'])) {
            throw new Exception('Only JPEG, PNG & GIF files are allowed.');
        }
        // if it passes all checks, try uploading file 
        if (!move_uploaded_file($file['tmp_name'], $target_file)) {
            throw new Exception('There was an error uploading your file.');
        }
        // if we reach this point, then everything worked out!
        echo 'The file ' . basename($file['name']) . ' has been uploaded.';
    } catch (Exception $e) {
        echo $e->getMessage();
    }
}

当然,验证可以得到更多改进 - 但这只是一个快速的例子。

最新更新