Yii resumable implementing

321 views Asked by At

I have a task to implement resumable in Yii, and I implemented upload control, but never Resumable before.

public function actionUpload()
    {
        $model=new User;
        if(isset($_POST['User'])) {
             $model->attributes=$_POST['User'];
             $model->image=CUploadedFile::getInstance($model,'image');
             if($model->save()) {
                 $model->image->saveAs('upload/'.$model->image->name);
                 $this->redirect(array('view','id'=>$model->uUserID));
             }
        }
        $this->render('upload',array('model'=>$model));
    }

The task is to chunk file in small pieces.

Example: one file can be 1 GB. And I try to send that file with rest service.

1

There are 1 answers

0
Maug Lee On

See Sample server implementation in PHP

I copy-paste here essential part of the code, provided on that page:

/**
 *
 * Check if all the parts exist, and 
 * gather all the parts of the file together
 * @param string $dir - the temporary directory holding all the parts of the file
 * @param string $fileName - the original file name
 * @param string $chunkSize - each chunk size (in bytes)
 * @param string $totalSize - original file size (in bytes)
 */
function createFileFromChunks($temp_dir, $fileName, $chunkSize, $totalSize) {

    // count all the parts of this file
    $total_files = 0;
    foreach(scandir($temp_dir) as $file) {
        if (stripos($file, $fileName) !== false) {
            $total_files++;
        }
    }

    // check that all the parts are present
    // the size of the last part is between chunkSize and 2*$chunkSize
    if ($total_files * $chunkSize >=  ($totalSize - $chunkSize + 1)) {

        // create the final destination file 
        if (($fp = fopen('temp/'.$fileName, 'w')) !== false) {
            for ($i=1; $i<=$total_files; $i++) {
                fwrite($fp, file_get_contents($temp_dir.'/'.$fileName.'.part'.$i));
                _log('writing chunk '.$i);
            }
            fclose($fp);
        } else {
            _log('cannot create the destination file');
            return false;
        }

        // rename the temporary directory (to avoid access from other 
        // concurrent chunks uploads) and than delete it
        if (rename($temp_dir, $temp_dir.'_UNUSED')) {
            rrmdir($temp_dir.'_UNUSED');
        } else {
            rrmdir($temp_dir);
        }
    }

}