簡體   English   中英

在服務器端處理 plupload 的分塊上傳

[英]Handling plupload's chunked uploads on the server-side

當我使用 plupload 對文件進行分塊(設置選項chunk_size )時,我會收到每個分塊的單獨 PHP 請求。 查看$_FILES變量,每個塊的類型都是"application/octet-stream"

是否有任何簡單、標准和舒適的方法如何在服務器端在 PHP 中組合這些部分?

保證健全(例如,當其中一件丟失時等)。

這是解析塊的方法,並將結果存儲在 $upload_file 中(更改 $uploaded_file 以匹配您需要的內容)。

    $uploaded_file = '/tmp/uploadFile.jpg';

    $chunks = isset($_POST["chunks"]) ? $_POST["chunks"] : 0;

    // If we have a chunked operation...
    if ($chunks > 0)
    {
        // Get the chunk number...
        $chunk = isset($_POST["chunk"]) ? $_POST["chunk"] : 0;

        if ($chunk == 0)
        {
           if (!isset($_SESSION['last_chunk']))
           {
              $_SESSION['last_chunk'] = array();
           }
           $_SESSION['last_chunk'][$_POST['unique_id']] = $chunk;
        }
        else
        {
           if ($_SESSION['last_chunk'][$_POST['unique_id']] != $chunk + 1)
           {
                die('{"jsonrpc" : "2.0", "error" : {"code": 192, "message": "Uploaded chunks out of sequence.  Try again."}, "id" : "id"}');
           }
        }

        $tmp_dir = sys_get_temp_dir();

        // We need a unique filename to identify the file...
        $tmp_filename = $tmp_dir.$_POST['unique_id'];

        // If it is the first chunk we have to create the file, othewise we append...
        $out_fp = fopen($tmp_filename, $chunk == 0 ? "wb" : "ab");

        // The file we are reading from...
        $uploaded_file = $_FILES['file']['tmp_name'];
        $in_fp = fopen($uploaded_file, "rb");

        // Copy the chunk that was uploaded, into the file we are uploading...
        while ($buff = fread($in_fp, 4096))
        {
            fwrite($out_fp, $buff);
        }
        fclose($out_fp);
        fclose($in_fp);


        // If we are the last chunk copy the file to the final location and continue on...
        if ($chunk == $chunks - 1)
        {
            copy($tmp_filename, $uploaded_file);
            unset($_SESSION['last_chunk'][$_POST['unique_id']]);
            if (count($_SESSION['last_chunk']) == 0)
            {  
                unset($_SESSION['last_chunk']);
            }
        }
        else
        {
            // Otherwise report the result to the uploader...
            echo'{"jsonrpc" : "2.0", "result" : null, "id" : "id"}';
        }
    }

最后,我使用了與 plupload-1.5.2 (examples/upload.php) 捆綁在一起的官方示例中的代碼:

http://github.com/moxiecode/plupload/blob/master/examples/upload.php

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM