dqellle310167 2018-06-18 21:25
浏览 57
已采纳

PHP MySQL jQuery上传多个文件到服务器问题

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.

  • 写回答

1条回答 默认 最新

  • doupu1727 2018-06-18 21:32
    关注

    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;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?