上传使用jQuery文件上传无效的文件

时间:2013-10-21 20:59:59

标签: javascript php jquery session file-upload

问题:

使用jQuery文件上传完成.txt文件上传后,设置会话变量并将用户重定向到不同的PHP页面。

HTML code(upload.php):

<!-- The fileinput-button span is used to style the file input field as button -->
<span class="btn btn-success fileinput-button">
    <i class="glyphicon glyphicon-plus"></i>
    <span>Add files...</span>
    <!-- The file input field used as target for the file upload widget -->
    <input id="fileupload" type="file" name="files[]" multiple>
</span>
<br>
<br>
<!-- The global progress bar -->
<div id="progress" class="progress">
    <div class="progress-bar progress-bar-success"></div>
</div>
<!-- The container for the uploaded files -->
<div id="files" class="files"></div>

jQuery代码(upload.php):

<script>    
    $(function () {
        'use strict';
        // Server-side upload handler:
        var url = 'process.php';

        $('#fileupload').fileupload({
            url: url,
            autoUpload: true,
            acceptFileTypes: /(\.|\/)(txt)$/i,
            maxFileSize: 5000000, // 5 MB
            done: function (e, data) {
                $(this).delay(2000, function(){
                    window.location = "explorer.php";
                });
            },
            progressall: function (e, data) {
                var progress = parseInt(data.loaded / data.total * 100, 10);
                $('#progress .progress-bar').css(
                    'width',
                    progress + '%'
                );
            }
        }).prop('disabled', !$.support.fileInput)
            .parent().addClass($.support.fileInput ? undefined : 'disabled');
    });
</script>

PHP上传脚本(process.php):

<?php
    session_start();

    $folder      = 'upload';

    if (!empty($_FILES))
    {
        // Set temporary name
        $tmp    = $_FILES['files']['tmp_name'];

        // Set target path and file name
        $target = $folder . '/' . $_FILES['files']['name'];

        // Upload file to target folder
        $status = move_uploaded_file($tmp, $target);

        if ($status)
        {
            // Set session with txtfile name
            $_SESSION['txtfile'] = $_FILES['files']['name'];
        }
    }
?>

期望的输出:

  • 文本文件应上传到文件夹/上传 - 目前有chmod 777
  • 应将文本文件名的会话分配给变量$ _SESSION ['txtfile']
  • 在上传文件“explorer.php”
  • 后重定向用户

编辑:已解决。上面的最终代码!

1 个答案:

答案 0 :(得分:3)

首先......

请注意,您的input名称为files[]且属性为multiple。这意味着你要向服务器发送一个文件数组,以便在php中引用它们,你需要这样的东西:

$_FILES['files']['name'][0]

表示第一个文件。

此外,我发现move_uploaded_file()喜欢目的地的完整路径,请尝试添加$_SERVER['DOCUMENT_ROOT']

要将信息发送回jQuery,您可能希望使用echo json_encode(),如此...

echo json_encode(array(
    'status' => $status,
    'message' => 'your message here'
));

done函数中,可以像这样访问数据:

done: function(e, data){
     console.log(data.status);
     console.log(data.message);
}