简体   繁体   中英

PHP MySQL jQuery Uploading Multiple Files to server issue

I just finished designing a basic site to upload some files to the server, and store the file names in a database for searching functions. I designed the site using the following tutorial: www.formget.com .

My problem is when I go to upload more than one file at a time, it appends the filenames together for a single file.

Example: Filename Example

Here is my code for uploading the files:

$error = '';

if(isset($_POST['submit']))
{
    $j = 0; // Variable for indexing uploaded image.
    $target_path = 'uploads/'; // Declare path for uploaded images.
    for($i = 0; $i < count($_FILES['file']['name']);$i++) // Loop to get individual element from the array.
    {
        $valid_ext = array('jpeg','jpg','png','gif'); // Extensions which are allowed.
        $ext = explode('.', basename($_FILES['file']['name'][$i])); // Explode file name from dot(.)
        $file_ext = end($ext); // Store extensions in the variable.
        $filename = md5(uniqid());
        $target_path = $target_path . $filename . '.' . $ext[count($ext) - 1]; // Set the target path with a new name of image.
        if(($_FILES['file']['size'][$i] < 5000000) // Approx. 5MB files can be uploaded.
        && in_array($file_ext,$valid_ext))
        {
            if(move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path))
            {
                // If file moved to uploads folder.
                $success .= '<p class="success">('.$j.') Image uploaded successfully.</p>';

                $date = date('Y-m-d H:i:s');

                $stmt = $db->prepare('INSERT INTO uploads (filename,postdate,userid) VALUES (?,?,?)');

                if($stmt)
                {
                    $image = $filename . '.' . $ext[count($ext) - 1];

                    $stmt->bind_param('sss',$image,$date,$_SESSION['id']);

                    if($stmt->execute())
                    {
                        $success .= '<p class="success">('.$j.') Image added to database successfully.</p>';
                    }
                    else
                    {
                        $error .= '<p class="error">Error 34. Please contact the Site Administrator.</p>';
                    }
                }
                else
                {
                    $error .= '<p class="error">Error 30. Please contact the Site Administrator.</p>';
                }
            }
            else
            {
                $error .= '<p class="error">('.$j.') Please Try Again!</p>';
            }
        }
        else
        {
            $error .= '<p class="error">('.$j.') Invalid file size or type.</p>';
        }

        $j = $j + 1; // Increment the number of uploaded images according to the files in the array.

    }
}

Here is the jQuery:

var abc = 0; // Declare and define global increment value.
$(document).ready(function()
{
    // To add new input file field dynamically, on click of "Add More Files" button, below function will be executed.
    $('#add_more').click(function()
    {
        $(this).before($("<div/>",
        {
            id: 'filediv'
        }).fadeIn('slow').append($("<input/>",
        {
            name: 'file[]',
            type: 'file',
            id: 'file'
        }), $("<br/><br/>")));
    });
    // Following function will execute on change event of file input to select different file.
    $('body').on('change', '#file', function()
    {
        if(this.files && this.files[0])
        {
            abc += 1; // Increment global variable by 1.

            var z = abc - 1;
            var x = $(this).parent().find('#previewimg' + z).remove();
            $(this).before("<div id='abcd" + abc + "' class='abcd'><img id='previewimg" + abc + "' src=''/></div>");
            var reader = new FileReader();
            reader.onload = imageIsLoaded;
            reader.readAsDataURL(this.files[0]);
            $(this).hide();
            $("abcd" + abc).append($("<img/>",
            {
                id: 'img',
                src: 'x.png',
                alt: 'delete'
            }).click(function()
            {
                $(this).parent().parent().remove();
            }));
        }
    });
    // To Preview Image
    function imageIsLoaded(e)
    {
        $('#previewimg' + abc).attr('src', e.target.result);
    };
    $('#upload').click(function(e)
    {
        var name = $(":file").val();
        if(!name)
        {
            alert("First Image Must Be Selected");
            e.preventDefault();
        }
    });
});

Any input as to why it keeps appending the filenames together would be appreciated. Please note that in the database, the filenames are correct, just not on the server itself in the uploads directory.

You are not resetting $target_path inside your for loop and therefore string concatenating it while looping. Results will be like A, AB, ABC, ... This is the issue:

$target_path = $target_path . $filename . '.' . $ext[count($ext) - 1];

You could create two variables.

$target_path = 'uploads/'; 

outside of your for-loop and use something like

 $move_to_target = $target_path . $filename . '.' . $ext[count($ext) - 1];

inside your for-loop and update your call of move_uploaded_file to pass $move_to_target instead of $target_path. Your database entries are not affected because you build up the filename again in $image - this however seems bad practice (redundant code), if you want to enhance your code define $image first and then create $move_to_target like this:

$move_to_target = $target_path . $image;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM