1) Encode form data
When we use the form to upload something, we need to encode the data.
25
26
27
28
29
30
31
32
33
34
35
36
|
<?php
\yii\bootstrap4\ActiveForm::begin([
'options' => ['enctype' => 'multipart/form-data']
])
?>
<button class="btn btn-primary btn-file">
Select File
<input type="file" name="video" id="videoFile">
</button>
<?php \yii\bootstrap4\ActiveForm::end() ?>
|
backend > view > video > create.php
2) Add event when video upload button is clicked
Create new file inside backend > web named app.js. Then
we load that file in AppAsset.php.
1
2
3
4
5
6
|
$(function () {
'use strict';
$('#videoFile').change(ev => {
$(ev.target).closest('form').trigger('submit');
})
});
|
backend > web > app.js
17
18
19
|
public $js = [
'app.js'
];
|
backend > assets > AppAsset.php
3) Write the logic to save the video file to storage
3
4
5
6
7
8
9
10
11
..
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
|
namespace backend\controllers;
use Yii;
use yii\web\Controller;
use common\models\Video;
use yii\web\UploadedFile;
use yii\filters\VerbFilter;
use yii\data\ActiveDataProvider;
use yii\web\NotFoundHttpException;
...
public function actionCreate()
{
$model = new Video();
$model->video = UploadedFile::getInstanceByName('video');
if ($this->request->isPost) {
if (Yii::$app->request->isPost && $model->save()) {
return $this->redirect(['view', 'video_id' => $model->video_id]);
}
} else {
$model->loadDefaultValues();
}
return $this->render('create', [
'model' => $model,
]);
}
|
backend > controllers > VideoController.php
3
4
5
6
..
24
25
26
27
28
29
..
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
|
namespace common\models;
use Yii;
use yii\helpers\FileHelper;
..
class Video extends \yii\db\ActiveRecord
{
/**
* \yii\web\UploadedFile
*/
public $video;
..
public function save($runValidation = true, $attributeNames = null)
{
$isInsert = $this->isNewRecord;
if ($isInsert) {
$this->video_id = Yii::$app->security->generateRandomString(8);
$this->title = $this->video->name;
$this->video_name = $this->video->name;
}
$saved = parent::save($runValidation, $attributeNames);
if (!$saved) {
return false;
}
if ($isInsert) {
$videoPath = Yii::getAlias('@frontend/web/storage/videos/' . $this->video_id . '.mp4');
if (!is_dir(dirname($videoPath))) {
FileHelper::createDirectory(dirname($videoPath));
}
$this->video->saveAs($videoPath);
}
return true;
}
|
common > models > Video.php
Let's try upload a video. You interface should look something like this after uploading a video (preferably short video).
Fix TypeError error when visiting /video/index
This problem occurs because we didn't import the Video class. It can easily be fixed with one line of code.
3
4
5
6
7
|
use yii\helpers\Url;
use yii\helpers\Html;
use yii\grid\GridView;
use common\models\Video;
use yii\grid\ActionColumn;
|
backend > views > video > index.php
No comments:
Post a Comment