首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >PHP MySQL jQuery上传多个文件到服务器的问题

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

Stack Overflow用户
提问于 2018-06-19 05:25:50
回答 1查看 23关注 0票数 1

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

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

示例:Filename Example

下面是我上传文件的代码:

代码语言:javascript
复制
$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:

代码语言:javascript
复制
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();
        }
    });
});

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-06-19 05:32:20

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

代码语言:javascript
复制
$target_path = $target_path . $filename . '.' . $ext[count($ext) - 1];

你可以创建两个变量。

代码语言:javascript
复制
$target_path = 'uploads/'; 

在for循环之外,并使用类似于

代码语言:javascript
复制
 $move_to_target = $target_path . $filename . '.' . $ext[count($ext) - 1];

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

代码语言:javascript
复制
$move_to_target = $target_path . $image;
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50917689

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档