2012-01-25 8 views
13

pluploadを使用してファイルをチャンク(設定オプションchunk_size)すると、チャンクごとに別々のPHPリクエストが得られます。 $_FILES変数を見ると、各チャンクはタイプ"application/octet-stream"です。サーバー側でpluploadのチャンクアップロードを処理する

サーバー側でこれらの部分をどのように組み合わせるのが簡単で標準的で快適な方法はありますか?

サニティが保証されている場合(たとえば、欠落している場合など)。

答えて

14

チャンクを解析し、その結果を$ 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"}'; 
     } 
    } 
+0

おかげクリス。その目的のために通常使用するコードですか? pluploadや別のライブラリで? – TMS

+0

私はpluploadのフラッシュコンポーネントでこれを使用します。チャンクを使用するすべてのpluploadと互換性があります。 –

+1

Kris、しかし私は$ _POST要求に 'unique_id'を持っていません。 pluploadオブジェクトの設定方法を教えてください。 'multipart:true'を使いますか? – TMS

関連する問題