繁体   English   中英

使用jQuery File Upload无法上传文件

[英]Upload files not working using jQuery File Upload

问题:

一旦使用jQuery File Upload完成.txt文件的上传,即可设置会话变量并将用户重定向到其他PHP页面。

HTML代码(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'];
        }
    }
?>

所需的输出:

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

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

对于初学者...

注意,您的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);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM