在服务器端处理plupload的分块上传

时间:2012-01-25 22:10:42

标签: php file-upload plupload chunked

当我使用plupload来块文件(设置选项chunk_size)时,我会为每个块获得一个单独的PHP请求。查看$_FILES变量,每个块的类型为"application/octet-stream"

有没有简单,标准和舒适的方法如何在服务器端将这些部分组合在一起?

保证理智(例如,当缺少其中一件时等)。

2 个答案:

答案 0 :(得分:16)

以下是解析块的方法,并将结果存储在$ 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"}';
        }
    }

答案 1 :(得分:5)

我终于使用了plupload-1.5.2(examples / upload.php)捆绑的官方示例中的代码:

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