How to create an uploading form in Yii Framework 2.0

Hi guys! In this tutorial I will explain to you how you can create an uploading form in Yii Framework 2.0. With Yii Framework 2.0 its very simple to create an uploading form. I will create the form by following the Yii documentation.

First of all, you need to create a model that will handle file uploads. Create a models/UploadForm.php file with this code:

namespace app\models;

use yii\base\Model;
use yii\web\UploadedFile;

/**
* UploadForm is the model behind the upload form.
*/
class UploadForm extends Model
{
/**
* @var UploadedFile file attribute
*/
public $file;

/**
* @return array the validation rules.
*/
public function rules()
{
return [
[['file'], 'file'],
];
}
}

Next, create a new view file, called upload with this content:

<?php
use yii\widgets\ActiveForm;
?>

<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]) ?>

<?= $form->field($model, 'file')->fileInput() ?>

<button>Submit</button>

<?php ActiveForm::end() ?>

At the top of your controller file, add this code:

use app\models\UploadForm;
use yii\web\UploadedFile;

Also, you must create a new action:

public function actionUpload()
{
$model = new UploadForm();

if (Yii::$app->request->isPost) {
$model->file = UploadedFile::getInstance($model, 'file');

if ($model->file && $model->validate()) {
$model->file->saveAs('uploads/' . $model->file->baseName . '.' . $model->file->extension);
}
}

return $this->render('upload', ['model' => $model]);
}

Next, create uploads folder in web folder. Your uploading form is ready!

Video tutorial:









Leave a Comment