Yii Framework Upload File

alfa6661
- March 01, 2013
0 (0 votes)
Rate :
Cara Mengupload file menggunakan Yii Framework

Artikel ini akan menjelaskan bagaimana cara mengupload file menggunakan Yii Framework.

Syntax

Model

Pertama, deklarasikan atribut baru untuk menyimpan file yang di upload pada class model dan buat aturan validasi pada atribut tersebut untuk memastikan file yang di upload sesuai dengan ekstensi file yang di tentukan.

class Product extends CActiveRecord
{
 
    public $image;
 
    public function rules()
    {
        return array(
            // rules image hanya menerima file jpg, gif dan png
            array('image', 'file', 'types'=>'jpg, gif, png'),
        );
    }
 
}

Controller

public function actionCreate()
{
    $model=new Product;
    if(isset($_POST['Product']))
    {
        $model->attributes = $_POST['Product'];
        $model->image = CUploadedFile::getInstance($model, 'image');
        if($model->save()) {
            $model->image->saveAs('/path/to/file');
            //....
        }
    }
    $this->render('create', array(
        'model' => $model
    ));
}

View

Selanjutnya buat view nya, pastikan anda mendeklarasikan form dengan enctype multipart/form-data

'htmlOptions' => array('enctype' => 'multipart/form-data'),
$form = $this->beginWidget('CActiveForm', array(
    'id' => 'upload-form',
    'enableAjaxValidation' => false,
    'htmlOptions' => array('enctype' => 'multipart/form-data'),
    )
);
echo $form->labelEx($model, 'image');
echo $form->fileField($model, 'image');
echo $form->error($model, 'image');
 
echo CHtml::submitButton('Submit');
$this->endWidget();

Computer science education cannot make anybody an expert programmer any more than studying brushes and pigment can make somebody an expert painter

– Eric S. Raymond

Have a better explanation?

If you have comments about this post. Please write your comments below

No comments associated with this article