【问题标题】:PHP MySQL jQuery Uploading Multiple Files to server issuePHP MySQL jQuery 将多个文件上传到服务器问题
【发布时间】:2018-06-18 21:25:50
【问题描述】:

我刚刚完成了一个基本站点的设计,将一些文件上传到服务器,并将文件名存储在数据库中以进行搜索功能。我使用以下教程设计了网站:www.formget.com

我的问题是,当我一次上传多个文件时,它会将文件名附加到一个文件中。

示例: Filename Example

这是我上传文件的代码:

$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.

    }
}

这里是 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();
        }
    });
});

任何关于为什么它不断将文件名附加在一起的输入将不胜感激。请注意,在数据库中,文件名是正确的,只是在服务器本身的上传目录中不正确。

【问题讨论】:

    标签: php jquery mysqli upload


    【解决方案1】:

    您没有在 for 循环中重置 $target_path ,因此在循环时将字符串连接起来。结果会像 A、AB、ABC、...这就是问题所在:

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

    你可以创建两个变量。

    $target_path = 'uploads/'; 
    

    在你的 for 循环之外并使用类似的东西

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

    在您的 for 循环中并更新您对 move_uploaded_file 的调用以传递 $move_to_target 而不是 $target_path。您的数据库条目不会受到影响,因为您在 $image 中再次建立文件名 - 但是这似乎是不好的做法(冗余代码),如果您想增强您的代码首先定义 $image 然后像这样创建 $move_to_target :

    $move_to_target = $target_path . $image;
    

    【讨论】:

    • 修复了它。感谢您的提示。
    猜你喜欢
    • 2012-04-02
    • 1970-01-01
    • 2017-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-27
    • 1970-01-01
    相关资源
    最近更新 更多