How to Add and Remove File Fields using jQuery and PHP

Today I’m going to share about multiple file upload in PHP. We’ll be using jQuery to add or remove new file fields. This one is useful when your system has multiple image upload or document management feature. You may also like How to Create Dynamic Add/Remove rows with input fields in HTML table using JavaScript and How to add option to select list using jQuery

HTML & jQuery Code

<html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
        <script type="text/javascript">
            function add_file()
            {
                $("#file_div").append("<div><input type='file' name='file[]'><input type='button' value='REMOVE' onclick=remove_file(this);></div>");
            }
            function remove_file(value)
            {
                $(value).parent().remove();
            }
        </script>
    </head>
    <body>
        <form method="post" action=""  enctype="multipart/form-data">
            <div id="file_div">
                <div>
                    <input type="file" name="file[]">
                    <input type="button" onclick="add_file();" value="ADD MORE">
                </div>
            </div>
            <input type="submit" name="submit_file" value="SUBMIT">
        </form>
    </body>
</html>

PHP Code

<?php
if (isset($_POST['submit_file'])) 
{
    for ($i = 0; $i < count($_FILES["file"]["name"]); $i++) 
    {
        $uploadfile = $_FILES["file"]["tmp_name"][$i];
        $folder = "images/";
        move_uploaded_file($_FILES["file"]["tmp_name"][$i], "$folder" . $_FILES["file"]["name"][$i]);
    }
}
?>

Leave a Reply

Your email address will not be published. Required fields are marked *