簡體   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