You’ll need to create a Database schema that holds information in BLOB type - this will be where the content is stored. I’ve attached my Model, Controller and View so you can compare the code etcetera and figure things out …
The SQL:
CREATE TABLE `tbl_abstract_img` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`chit_id` int(11) DEFAULT NULL,
`create_time` datetime DEFAULT NULL,
`create_user_id` int(11) DEFAULT NULL,
`update_time` datetime DEFAULT NULL,
`update_user_id` int(11) DEFAULT NULL,
`file_name` varchar(128) DEFAULT NULL,
`file_type` varchar(128) DEFAULT NULL,
`file_size` int(11) DEFAULT NULL,
`file_content` blob,
PRIMARY KEY (`id`),
UNIQUE KEY `id` (`id`),
KEY `FK_abstract_img_chit` (`chit_id`),
KEY `FK_abstract_img_author` (`create_user_id`),
CONSTRAINT `FK_abstract_img_author` FOREIGN KEY (`create_user_id`) REFERENCES `tbl_user` (`id`),
CONSTRAINT `FK_abstract_img_chit` FOREIGN KEY (`chit_id`) REFERENCES `tbl_chit` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 |
The View:
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'abstract-image-form',
'enableAjaxValidation'=>false,
'htmlOptions'=>array(
'enctype' => 'multipart/form-data',
)
)); ?>
<p class="note">Fields with <span class="required">*</span> are required.</p>
<?php echo $form->errorSummary($model); ?>
<div class="row">
<?php echo $form->labelEx($model,'uploadedFile'); ?>
<?php echo $form->fileField($model,'uploadedFile'); ?>
<?php echo $form->error($model,'uploadedFile'); ?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save'); ?>
</div>
<?php $this->endWidget(); ?>
</div><!-- form -->
The Model:
class AbstractImage extends CActiveRecord
{
public $uploadedFile;
/**
* Returns the static model of the specified AR class.
* @return AbstractImage the static model class
*/
public static function model($className=__CLASS__)
{
return parent::model($className);
}
/**
* @return string the associated database table name
*/
public function tableName()
{
return 'tbl_abstract_img';
}
/**
* @return array validation rules for model attributes.
*/
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
//array('chit_id, create_user_id, update_user_id, file_size', 'numerical', 'integerOnly'=>true),
//array('file_name, file_type', 'length', 'max'=>128),
//array('create_time, update_time, file_content', 'safe'),
// The following rule is used by search().
// Please remove those attributes that should not be searched.
//array('id, chit_id, create_time, create_user_id, update_time, update_user_id, file_name, file_type, file_size, file_content', 'safe', 'on'=>'search'),
array('uploadedFile', 'file', 'allowEmpty'=>false, 'on' => 'insert'),
array('uploadedFile', 'file', 'allowEmpty'=>true, 'on' => 'update'),
);
}
/**
* @return array relational rules.
*/
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
'createUser' => array(self::BELONGS_TO, 'User', 'create_user_id'),
'chit' => array(self::BELONGS_TO, 'Chit', 'chit_id'),
'author' => array(self::BELONGS_TO, 'User', 'create_user_id'),
);
}
/**
* @return array customized attribute labels (name=>label)
*/
public function attributeLabels()
{
return array(
'id' => 'ID',
'chit_id' => 'Chit',
'create_time' => 'Create Time',
'create_user_id' => 'Create User',
'update_time' => 'Update Time',
'update_user_id' => 'Update User',
'file_name' => 'File Name',
'file_type' => 'File Type',
'file_size' => 'File Size',
'file_content' => 'File Content',
);
}
/**
* Retrieves a list of models based on the current search/filter conditions.
* @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
*/
public function search()
{
// Warning: Please modify the following code to remove attributes that
// should not be searched.
$criteria=new CDbCriteria;
$criteria->compare('id',$this->id);
$criteria->compare('chit_id',$this->chit_id);
$criteria->compare('create_time',$this->create_time,true);
$criteria->compare('create_user_id',$this->create_user_id);
$criteria->compare('update_time',$this->update_time,true);
$criteria->compare('update_user_id',$this->update_user_id);
$criteria->compare('file_name',$this->file_name,true);
$criteria->compare('file_type',$this->file_type,true);
$criteria->compare('file_size',$this->file_size);
$criteria->compare('file_content',$this->file_content,true);
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}
public function beforeSave()
{
$file=CUploadedFile::getInstance($this,'uploadedFile');
if($file)
{
$this->file_name=$file->name;
$this->file_type=$file->type;
$this->file_size=$file->size;
$this->file_content=file_get_contents($file->tempName);
}
if(!empty ($this->create_user_id)) {
$this->update_user_id=Yii::app()->user->id;
$this->update_time=date('Y-m-d H:i:s');
}
if(empty($this->create_user_id)) {
$this->create_user_id=Yii::app()->user->id;
$this->create_time=date('Y-m-d H:i:s');
}
return parent::beforeSave();
}
}
The Controller:
<?php
class AbstractImageController extends Controller
{
/**
* @var string the default layout for the views. Defaults to '//layouts/column2', meaning
* using two-column layout. See 'protected/views/layouts/column2.php'.
*/
public $layout='//layouts/column2';
/**
* @return array action filters
*/
public function filters()
{
return array(
'accessControl', // perform access control for CRUD operations
);
}
/**
* Specifies the access control rules.
* This method is used by the 'accessControl' filter.
* @return array access control rules
*/
public function accessRules()
{
return array(
array('allow', // allow all users to perform 'index' and 'view' actions
'actions'=>array('index','view','displaysavedimage'),
'users'=>array('*'),
),
array('allow', // allow authenticated user to perform 'create' and 'update' actions
'actions'=>array('create','update'),
'users'=>array('@'),
),
array('allow', // allow admin user to perform 'admin' and 'delete' actions
'actions'=>array('admin','delete'),
'users'=>array('admin'),
),
array('deny', // deny all users
'users'=>array('*'),
),
);
}
/**
* Displays a particular model.
* @param integer $id the ID of the model to be displayed
*/
public function actionView($id)
{
$this->render('view',array(
'model'=>$this->loadModel($id),
));
}
/**
* Creates a new model.
* If creation is successful, the browser will be redirected to the 'view' page.
*/
public function actionCreate()
{
$model=new AbstractImage;
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['AbstractImage']))
{
$model->attributes=$_POST['AbstractImage'];
if($model->save())
$this->redirect(array('view','id'=>$model->id));
}
$this->render('create',array(
'model'=>$model,
));
}
/**
* Updates a particular model.
* If update is successful, the browser will be redirected to the 'view' page.
* @param integer $id the ID of the model to be updated
*/
public function actionUpdate($id)
{
$model=$this->loadModel($id);
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['AbstractImage']))
{
$model->attributes=$_POST['AbstractImage'];
if($model->save())
$this->redirect(array('view','id'=>$model->id));
}
$this->render('update',array(
'model'=>$model,
));
}
/**
* Deletes a particular model.
* If deletion is successful, the browser will be redirected to the 'admin' page.
* @param integer $id the ID of the model to be deleted
*/
public function actionDelete($id)
{
if(Yii::app()->request->isPostRequest)
{
// we only allow deletion via POST request
$this->loadModel($id)->delete();
// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
if(!isset($_GET['ajax']))
$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
}
else
throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
}
/**
* Lists all models.
*/
public function actionIndex()
{
$dataProvider=new CActiveDataProvider('AbstractImage');
$this->render('index',array(
'dataProvider'=>$dataProvider,
));
}
/**
* Manages all models.
*/
public function actionAdmin()
{
$model=new AbstractImage('search');
$model->unsetAttributes(); // clear any default values
if(isset($_GET['AbstractImage']))
$model->attributes=$_GET['AbstractImage'];
$this->render('admin',array(
'model'=>$model,
));
}
/**
* Returns the data model based on the primary key given in the GET variable.
* If the data model is not found, an HTTP exception will be raised.
* @param integer the ID of the model to be loaded
*/
public function loadModel($id)
{
$model=AbstractImage::model()->findByPk($id);
if($model===null)
throw new CHttpException(404,'The requested page does not exist.');
return $model;
}
/**
* Performs the AJAX validation.
* @param CModel the model to be validated
*/
protected function performAjaxValidation($model)
{
if(isset($_POST['ajax']) && $_POST['ajax']==='abstract-image-form')
{
echo CActiveForm::validate($model);
Yii::app()->end();
}
}
public function actionDisplaySavedImage()
{
$model=$this->loadModel($_GET['id']);
header('Pragma: public');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Content-Transfer-Encoding: binary');
header('Content-length: '.$model->file_size);
header('Content-Type: '.$model->file_type);
header('Content-Disposition: attachment; filename='.$model->file_name);
echo $model->file_content;
}
}
I hope this helps.