5

Am using HTML to upload images and process form in PHP in my form i need the following

  • Maximum file only 5 file user can upload
  • i need to store all image name to SQL database

HTML

<input type="file" id="files" name="files[]" multiple/>

SCRIPT

<script src="http://code.jquery.com/jquery-1.11.1.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(document).ready(function() {

            if (window.File && window.FileList && window.FileReader) {
                $("#files").on("change", function(e) {
                    var files = e.target.files,
                            filesLength = files.length;
                    for (var i = 0; i < filesLength; i++) {
                        var f = files[i]
                        var fileReader = new FileReader();
                        fileReader.onload = (function(e) {
                            var file = e.target;
                            $("<img></img>", {
                                class: "imageThumb",
                                src: e.target.result,
                                title: file.name
                            }).insertAfter("#files");
                        });
                        fileReader.readAsDataURL(f);
                    }
                });
            } else {
                alert("Your browser doesn't support to File API")
            }
        });
    </script>

FORM PROCESSING

$file = filter_input(INPUT_POST, 'file', FILTER_SANITIZE_STRING);
$file1 = filter_input(INPUT_POST, 'file1', FILTER_SANITIZE_STRING);
$file2 = filter_input(INPUT_POST, 'file2', FILTER_SANITIZE_STRING);
$file3 = filter_input(INPUT_POST, 'file3', FILTER_SANITIZE_STRING);
$file4 = filter_input(INPUT_POST, 'file4', FILTER_SANITIZE_STRING);

withe the above code i need to store image name to SQL database

sanoj lawrence
  • 1,085
  • 4
  • 24
  • 55

5 Answers5

2

I would suggest that you take a look here :

how can I upload multiple files at a single browse using jquery or JavaScript

and here :

Count and limit the number of files uploaded (HTML file input)

Community
  • 1
  • 1
Michael Laffargue
  • 9,799
  • 6
  • 39
  • 74
2

You have to use in your PHP a code like this

$conexion = mysqli_connect("Servername", "usernameDB", "PasswordDB", "nameDB");
if (isset($_FILES['files'])) {

    if (sizeof($_FILES['files']['tmp_name']) > 5) {
        exit("max 5 files allowed");
    }

    foreach ($_FILES['files']['error'] as $key => $value) {

        switch($value) {
            case (0):
                if (exif_imagetype($_FILES['files']['tmp_name'][$key])) {
                    $dome_dir = "imaged/uploaded/";
                    // do something with the file, for example move it.
                    move_uploaded_file($_FILES['files']['tmp_name'], $some_dir . $_FILES['name']);
                    $message = "is a image... Uploaded";
                    // take care, if the name are equals that something storaged, will overwrite the old file
                    $filename = mysqli_real_string_escape($conexion, $_FILES['files']['name'][$key]);
                    $store_image = $some_dir . $filename;
                    $sql = "INSERT INTO tablename(ID, IMAGE_ROUTE) VALUES(NULL, '$store_image')";
                    if(mysqli_query($conexion, $sql)){
                        echo 'Image ' . $_FILES['files']['name'][$key] . ' saved successful';
                    } else {
                        echo "An error has ocurred with the database saving the image";
                    }
                } else {
                    $message = "isn't a image";
                }
                break;
            case 1:
                $message = 'is too big';
                break;
            case 2: 
                $message = 'is too big';
                break;
            case 3:
                $message = "wasn't uploaded complete";
                break;
            case 4:
                $message = "wasn't uploaded";
                break;
            default:
                $message = "Error: file wasn't uploaded";
                break;
        }
        echo "The file name: " . $_FILES['files']['name'][$key] . ' ' . $message . '<br>';
    }
}

And your HTML put something like this

<form id="form" method="post" enctype="multipart/form-data">
    <input type="file" name="files[]" multiple>
    <input type="submit" value="Submit">
</form>

In your JS put something like this

$(document).ready(function() {
    $('#form').on('submit', function(e) {
        var $fileUpload = $("input[type='file']");
        if (parseInt($fileUpload.get(0).files.length)>5){
            e.preventDefault();
            alert("You can only upload a maximum of 5 files");
        } else if (parseInt($fileUpload.get(0).files.length) == 0) {
            e.preventDefault();
            alert("Choose almost one file");
        }
    });
});

I hope this help you :)

Erick Jimenez
  • 328
  • 1
  • 12
1

You are possibly expecting that the user can do all this multiple times:

click browse > select a file > file shows up

But the way the multi-file upload works is that you select multiple files in the file browser once (holding CTRL). These are the files that gets passed to the $_FILE variable. I you do it multiple times only the last selected file gets passed

edit: if you want to clarify this to the user, you should remove all the image tags on each file browsing event, so only the one(s) selected the last time show up

test to reflect this:

<html>
    <body>
        <pre><?
        foreach ($_FILES['files']['name'] as $fileName  ) {
            echo $fileName."\n";
        }
    ?></pre>
        <form method="post" enctype="multipart/form-data">
            <input name="files[]" type="file" />
            <input name="submit" type="submit" />
        </form>
    </body>
</html>
BobbyTables
  • 3,498
  • 1
  • 22
  • 28
1

Edited again to reflect the posters new wishes of how the user experience should be. Now has a drag-drop with preview OR manual selection of 5 files. The drag-drop is submitted by a ajax post, so watch the console for the result. Display and flow needs to be streamlined, but shows a technical working example. The same PHP code handles both results.

<html>
    <body>
        <pre><?
            print_r($_FILES); //SHOW THE ARRAY

            foreach ($_FILES as $file) {
                if (!$file['error']) {
                    //PROCESS THE FILE HERE
                    echo $file['name'];
                }
            }
        ?></pre>

        <script src="http://code.jquery.com/jquery-1.11.1.min.js" type="text/javascript"></script>
        <script type="text/javascript">

            var fd = new FormData(); 
            $(document).ready(function() {

                //submit dragdropped by ajax
                $("#dropsubmit").on("click", function(e) {
                     $.ajax({           
                        data: fd,
                        processData: false,
                        contentType: false,
                        type: 'POST',
                        success: function(data){
                            //FILES POSTED OK! REDIRECT
                            console.log(data);
                        }
                      });
                })

                var dropzone = $("#dropzone");
                dropzone.on('dragenter', function (e) {
                    $(this).css('background', 'lightgreen');
                });

                //dropped files, store as formdata
                dropzone.on('dragover', stopPropagate);
                dropzone.on('drop', function (e) {
                    stopPropagate(e)
                    $(this).css('background', 'white');
                     var files = e.originalEvent.dataTransfer.files;

                     for (var i = 0; i < files.length; i++)  {
                        preview(files[i])
                        fd.append('file' + (i + 1), files[i]);
                        if (i >= 5) continue
                     }

                });
                function stopPropagate(e) {
                    e.stopPropagation();
                    e.preventDefault();
                } 


                if (window.File && window.FileList && window.FileReader) {
                    $("input[type=file]").on("change", function(e) {
                        preview(e.target.files[0])
                    });
                } else {
                    alert("Your browser doesn't support to File API")
                }

                function preview(item) {
                    var fileReader = new FileReader();
                    fileReader.onload = (function(e) {
                        var file = e.target;
                        $("<img></img>", {
                            class: "imageThumb",
                            src: file.result,
                            title: file.name,
                        }).appendTo("#images");
                    });
                    fileReader.readAsDataURL(item);
                }
            });
        </script>

        <div id="dropzone" style="width:100px;height:100px;border:2px dashed gray;padding:10px">Drag & Drop Files Here</div>
        <input type="button" id="dropsubmit" value="Submit dropped files" />
        <hr>
        <form method="post" enctype="multipart/form-data">
            <input id="file1" name="file1" type="file"/><br>
            <input id="file2" name="file2" type="file"/><br>
            <input id="file3" name="file3" type="file"/><br>
            <input id="file4" name="file3" type="file"/><br>
            <input id="file5" name="file3" type="file"/><br>
            <input name="submit" type="submit" value="Upload files" />
        </form><div id="images"></div>
    </body>
</html>
BobbyTables
  • 3,498
  • 1
  • 22
  • 28
  • i cant add more than one file – sanoj lawrence Nov 13 '14 at 10:51
  • yes you can, but you cannot do it by clicking "browse" multiple times. This is not how the controller works by design. You click browse once, and select multiple files by holding CTRL in the file-browser window – BobbyTables Nov 13 '14 at 10:54
  • how can i make it multiple times – sanoj lawrence Nov 13 '14 at 10:58
  • well, in that case you have to use separate input elements, and not one input element with the "multiple" tag. The php $FILES array will then hold all instances of the files – BobbyTables Nov 13 '14 at 11:14
  • how to make drag and drop option If client feels lazy they will drag and drop file when user drops file it should fill all five elements make this and take your reward :) – sanoj lawrence Nov 13 '14 at 12:13
  • the input-file elements are read-only so they cannot be modified by javascript on a drag-drop operation. You would have to manage separate form-data with the dropped files and submit those in that case. If this information was availible from the start i would have chosen a different approach than the current – BobbyTables Nov 13 '14 at 13:18
  • http://www.sitepoint.com/html5-file-drag-and-drop/ a multiple drag drop input file but here i do'n have image preview – sanoj lawrence Nov 13 '14 at 13:27
  • i have updated with an example that also shows a drag-drop form thats submits via AJAX to the same form. – BobbyTables Nov 13 '14 at 13:50
  • that's perfect this is what i want one small option i need in that how do i process the file name to SQL table limit only 5 file only this option your ready to take reward – sanoj lawrence Nov 13 '14 at 14:34
  • 1
    ...and i ll give you an up-vote if you do a barrel roll. maybe. – Sharky Nov 13 '14 at 14:59
  • please help how to process multiple image to SQL table – sanoj lawrence Nov 13 '14 at 15:21
  • How this works ?? when i drop file drop box the file is move to file input bellow this the method or how??? – sanoj lawrence Nov 14 '14 at 04:37
1

This code is not allows you to upload more then 5 files. At here, the trick, is to reset the input type file, is that, you'v just clone, and replace the previous. I tried with this.reset, but the text of how many file added has remained.

    if (window.File && window.FileList && window.FileReader) {
        $("#files").on("change", function(e) {
            var files = e.target.files;
            var filesLength = files.length;
            var allowedCnt = 5;
            if (filesLength > allowedCnt) {
                $(this).replaceWith($(this).val('').clone(true));
                alert('Can not add more then ' + allowedCnt + ' files');
                return false;
            } else {

                for (var i = 0; i < filesLength; i++) {
                    var f = files[i]
                    var fileReader = new FileReader();
                    fileReader.onload = (function(e) {
                        var file = e.target;
                        $("<img></img>", {
                            class: "imageThumb",
                            src: e.target.result,
                            title: file.name
                        }).insertAfter("#files");
                    });
                    fileReader.readAsDataURL(f);
                }
            }
        });
    } else {
        alert("Your browser doesn't support to File API")
    }

HTML

<form method="POST" action="" id="myform" enctype="multipart/form-data">
    <input type="file" id="files" name="files[]" multiple /><br />
    <input type="submit" name="submit" value="submit"  />
</form>

PHP At here just simple connect to database, and add the items to your table as you want with a foreach loop. Of course, you can do a server side check or validation here also!

if (isset($_POST["submit"])) {
    $link = mysqli_connect("myhost", "myuser", "mypassw", "mybd") or die("Error " . mysqli_error($link));
    foreach (array_keys($_FILES['files']['tmp_name']) as $key) {
        //Moving file where you want.
        mysqli_query($link, "INSERT INTO tblName (fieldName) VALUES ('" . mysqli_real_escape_string($_FILES["files"]['name'][$key]) . "')");
    }
}
vaso123
  • 12,011
  • 4
  • 28
  • 59