Anil
Anil

Reputation: 43

I Want To Upload Multiple Files and than enter their Title with particular and than want to store in database by clicking on submit

Need help to create form for multiple upload with dynamically added multiple text input box

For Uploading File to Server

if(isset($_POST['submit']))
    {
        $count=count($_FILES['files']['name']);

        for($i=0;$i<$count;$i++)
        {
            $allowed = array("mp3" => "audio/mp3","wav" => "audio/wav");

            $cat_type = $_POST['cat_type'];

            $title = $_POST['title'][$i];

            $filename= $_FILES['files']['name'][$i];
            $tempfilename= $_FILES['files']['tmp_name'][$i];
            $filetype=$_FILES['files']['type'][$i];
            $filesize = $_FILES['files']['size'][$i];

            // Verify file extension
            $video_ext = pathinfo($filename, PATHINFO_EXTENSION);
            if(!array_key_exists($video_ext, $allowed)) die("Error: Please select a valid file format.");

            // Verify file size - 5MB maximum
            $maxsize = 5 * 1024 * 1024;
            if($filesize > $maxsize) die("Error: File size is larger than the allowed limit.");

            // Verify MYME type of the file
            if(in_array($filetype, $allowed))
            {
                // Check whether file exists before uploading it
                if(file_exists($ringtonelocation . $filename))
                {
                    echo $filename . " is already exists.";
                } 
                else
                {
                    //uploading file and storing it to database as well 
                    try
                    {
                        $cat_type = $_POST['cat_type'];

                        $cat_alias = strtolower(preg_replace('/\s+/', '', $cat_type));
                        $highest_id += 1;

                        $uploaddate= date("d-m-Y_h-i-sa");
                        // Rename file
                        $newvideofilename = strtolower(str_replace(" ", "_",$title)). "_" .$highest_id. "_" .$uploaddate .".".$video_ext;   


                        move_uploaded_file($_FILES['files']['tmp_name'][$i],$videolocation.$newvideofilename);
                        // $filepath="upload/".$filename;

                        // echo "<br/> Category:-".$cat_type;
                        // echo "<br/> Title:-".$title;
                        // echo "<br/> File Name:-".$filename;
                        // echo "<br/> Record Insert successfully";
                        // echo "<br/>";
                        // $sql = "INSERT INTO video_master (id, name , url) VALUES (NULL,'$title','$filepath')";
                        $sql = "INSERT INTO ringtone_master 
                                (id, name ,cat_type, cat_alias, url, downloads, views, fav_counter, likes, dislikes) 
                                VALUES 
                                (NULL,'$title','$cat_type','$cat_alias','$newvideofilename',0,0,0,0,0)";
                        if(mysqli_query($con,$sql))
                        {
                            echo "<br/> Record Insert successfully";
                        }
                        else
                        {
                            echo "Error: " . $sql . "<br>" . mysqli_error($con);
                        }
                    }
                    catch(Exception $e)
                    {
                        $response['error'] = true;
                        $response['message'] = 'Could not upload file1....';
                    }
                } 

            }
        }
    }

Temporary store file in browser

 <script>
    var selDiv = "";
    var storedFiles = [];

    $(document).ready(function() {
        $("#files").on("change", handleFileSelect);

        selDiv = $("#selectedFiles"); 
        $("#myForm").on("submit", handleForm);

        $("body").on("click", ".selFile", removeFile);
    });

    function handleFileSelect(e) {
        var files = e.target.files;
         var filesArr = Array.prototype.slice.call(files);

        filesArr.forEach(function(f) {          

            if(!f.type.match("audio.mp3")) {
                return;
            }
            storedFiles.push(f);

            var reader = new FileReader();
            reader.onload = function (e) {
                // var html = "<div><img src=\"" + e.target.result + "\" data-file='"+f.name+"' class='selFile' title='Click to remove'>" + f.name + "<br clear=\"left\"/></div>";

                var html = "<div><input type='text' name='title[] required'>"+ f.name + "</div>";
                selDiv.append(html);

            }
            reader.readAsDataURL(f); 
        });   
    }
    </script>

Html portion

    <br><br>
    <label for="fileSelect">Select Video to Upload:</label>&nbsp;
       <input type="file" id="files" name="files[]" multiple>
    <br><br>
    <div id="selectedFiles"></div>
    <input type="submit" name="submit" value="Upload">

When i Choose Multiple files it will generate number of input field as per uploaded file but the issue is that input field and files are not in same order

So Please help to solve this Thank You

Upvotes: 0

Views: 322

Answers (1)

NosFreat
NosFreat

Reputation: 41

Alright taking a step back i noticed i failed to mention quite a few things, also to correct it I've used a different implementation than the one i suggested, the following works for me.

Change your handleFileSelect to the following:

function handleFileSelect(e) {
    var files = e.target.files;
     var filesArr = Array.prototype.slice.call(files);

    filesArr.forEach(function(f,index) {          

        if(!f.type.match("audio.mp3")) {
            return;
        }
        storedFiles.push(f);

        var reader = new FileReader();
        reader.onload = function (e) {
            // var html = "<div><img src=\"" + e.target.result + "\" data-file='"+f.name+"' class='selFile' title='Click to remove'>" + f.name + "<br clear=\"left\"/></div>";

            var html = "<div><input type='text' name='title["+index+"] required'>"+ f.name + "</div>";
            selDiv.append(html);

        }
        reader.readAsDataURL(f); 
    });   
}

Then in your php code you can switch back to doing the following:

if(isset($_POST['submit']))
{
    $count=count($_FILES['files']['name']);

    for($i=0;$i<$count;$i++)
    {
        $allowed = array("mp3" => "audio/mp3","wav" => "audio/wav");

        $cat_type = $_POST['cat_type'];

        $title = $_POST['title'][$i];

        $filename= $_FILES['files']['name'][$i];
        $tempfilename= $_FILES['files']['tmp_name'][$i];
        $filetype=$_FILES['files']['type'][$i];
        $filesize = $_FILES['files']['size'][$i];

        // Verify file extension
        $video_ext = pathinfo($filename, PATHINFO_EXTENSION);
        if(!array_key_exists($video_ext, $allowed)) die("Error: Please select a valid file format.");

        // Verify file size - 5MB maximum
        $maxsize = 5 * 1024 * 1024;
        if($filesize > $maxsize) die("Error: File size is larger than the allowed limit.");

        // Verify MYME type of the file
        if(in_array($filetype, $allowed))
        {
            // Check whether file exists before uploading it
            if(file_exists($ringtonelocation . $filename))
            {
                echo $filename . " is already exists.";
            } 
            else
            {
                //uploading file and storing it to database as well 
                try
                {
                    $cat_type = $_POST['cat_type'];

                    $cat_alias = strtolower(preg_replace('/\s+/', '', $cat_type));
                    $highest_id += 1;

                    $uploaddate= date("d-m-Y_h-i-sa");
                    // Rename file
                    $newvideofilename = strtolower(str_replace(" ", "_",$title)). "_" .$highest_id. "_" .$uploaddate .".".$video_ext;   


                    move_uploaded_file($_FILES['files']['tmp_name'][$i],$videolocation.$newvideofilename);
                    // $filepath="upload/".$filename;

                    // echo "<br/> Category:-".$cat_type;
                    // echo "<br/> Title:-".$title;
                    // echo "<br/> File Name:-".$filename;
                    // echo "<br/> Record Insert successfully";
                    // echo "<br/>";
                    // $sql = "INSERT INTO video_master (id, name , url) VALUES (NULL,'$title','$filepath')";
                    $sql = "INSERT INTO ringtone_master 
                            (id, name ,cat_type, cat_alias, url, downloads, views, fav_counter, likes, dislikes) 
                            VALUES 
                            (NULL,'$title','$cat_type','$cat_alias','$newvideofilename',0,0,0,0,0)";
                    if(mysqli_query($con,$sql))
                    {
                        echo "<br/> Record Insert successfully";
                    }
                    else
                    {
                        echo "Error: " . $sql . "<br>" . mysqli_error($con);
                    }
                }
                catch(Exception $e)
                {
                    $response['error'] = true;
                    $response['message'] = 'Could not upload file1....';
                }
            } 

        }
    }
}

As long as you don't change the order of the files in some other way, the added index for the foreach in the script will give each title the same index as the file has in it's files array, meaning they will follow each-others index.

Which means on the php end they'll also follow each-other- the solution above works on my end, i suspect that if it doesn't work on your end you have something changing the order of the index's and further investigation is required.

Upvotes: 1

Related Questions