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

报告相同问题?

悬赏问题

  • ¥20 我要一个分身加定位两个功能的安卓app
  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助
  • ¥15 STM32控制MAX7219问题求解答