tjtjtjのメモ

自分のためのメモです

ファイルアップロード

yiiでファイルアップロードしてみる。アップロードしたファイルはMySQL BLOBに保存する。

テーブルを作る

create table `file` (
  `id` INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `name` varchar(255) not null,
  `type` varchar(64) not null,
  `size` float not null,
  `content` BLOB not null
)
;

モデルを作る

yiifile\protected\models\File.php

<?php
class File extends CActiveRecord
{
	public $name;
 	public $type;
 	public $size;
 	public $content;

 	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}
 	
}

createアクションを作る

yiifile\protected\controllers\FilesController.php

<?php
class FilesController extends Controller
{
	public function actionCreate()
	{
		$model = new File;

		if(isset($_POST['File']))
		{
			$temp = CUploadedFile::getInstance($model, 'file');
			$model->name = $temp->name;
			$model->type = $temp->type;
			$model->size = $temp->size;
			$model->content = file_get_contents($temp->tempName);
			unlink($temp->tempName);

			if($model->save())
			$this->redirect(array('view','id'=>$model->id));
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}
}

createビューを作る

yiifile\protected\views\files\create.php

<h1>Create File</h1>

<?php $form=$this->beginWidget('CActiveForm', array(
	'id'=>'entry-form',
	'htmlOptions' => array('enctype'=>'multipart/form-data'),
)); ?>

	<div class="row">
		<?php echo $form->fileField($model,'file'); ?>
	</div>

	<div class="row buttons">
		<?php echo CHtml::submitButton('Save'); ?>
	</div>

<?php $this->endWidget(); ?>

Createページでファイルを選択し、SaveボタンをクリックするとFileテーブルに入ってるはず。

viewアクションを作る

アップロードしたファイルをブラウザで表示してみよう。

yiifile\protected\controllers\FilesController.php

<?php
class FilesController extends Controller
{
	public function actionView()
	{
		$model = File::model()->findByPk($_GET['id']);

		header('Content-Type: '.$model->type);
		echo $model->content;
	}
}

これでアップロードするとブラウザで表示する。