Yii可恢复实施

时间:2014-05-31 14:05:49

标签: php file-upload yii resume-upload resumablejs

我有一个在Yii中实现可恢复的任务,我实现了上传控制,但之前从未进行过Resumable。

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));
    }

任务是将文件分块。

示例:一个文件可以是1 GB。我尝试用休息服务发送该文件。

1 个答案:

答案 0 :(得分:0)

请参阅Sample server implementation in PHP

我复制粘贴代码的重要部分,在该页面上提供:

/**
 *
 * 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);
        }
    }

}