Upload file menggunakan kartik fileinput widget :
Langkah 1 : Install Yii2 Extension Kartik FileInput
1 |
composer require kartik-v/yii2-widget-fileinput "@dev" |
Langkah 2 : Buat Tabel dan Model
Pada contoh ini, kita akan membuat tabel file dan model File dengan Gii.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
<?php namespace common\models; use Yii; /** * This is the model class for table "file". * * @property integer $id * @property string $namafile */ class File extends \yii\db\ActiveRecord { /** * @inheritdoc */ public static function tableName() { return 'file'; } /** * @inheritdoc */ public function rules() { return [ [['namafile'], 'string', 'max' => 100], ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'id' => Yii::t('app', 'ID'), 'namafile' => Yii::t('app', 'Namafile'), ]; } } |
Langkah 3 : Persiapkan Controller dan View
Siapkan FileController.php kemudian tambahkan beberapa action sebagai berikut :
1. public function actionIndex : Untuk menampilkan data
1 2 3 4 5 6 |
public function actionIndex(){ $files = File::find()->all(); return $this->render('index',[ 'files' => $files, ]); } |
2. public function actionCreate : Untuk menampilkan form dan mengupload File
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
public function actionCreate() { $model = new File(); if ($model->load(Yii::$app->request->post())) { $model->namafile = UploadedFile::getInstance($model,'namafile'); if($model->namafile){ $file = $model->namafile->name; if ($model->namafile->saveAs(Yii::getAlias('@frontend').'/web/file/'.$file)){ $model->namafile = $file; } } $model->save(); return $this->redirect(['index']); } else { return $this->render('create', [ 'model' => $model, ]); } } |
3. public function actionUpdate : Untuk mengupdate File
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
public function actionUpdate($id) { $model = $this->findModel($id); $old_file = $model->namafile; if ($model->load(Yii::$app->request->post())) { $model->namafile = UploadedFile::getInstance($model,'namafile'); if($model->namafile){ $file = $model->namafile->name; if ($model->namafile->saveAs(Yii::getAlias('@frontend').'/web/file/'.$file)){ $model->namafile = $file; } } if (empty($model->namafile)){ $model->namafile = $old_file; } $model->save(); return $this->redirect(['index']); } else { return $this->render('update', [ 'model' => $model, ]); } } |
4. public function actionDelete : Untuk menghapus File
1 2 3 4 5 6 7 |
public function actionDelete($id) { $model = $this->findModel($id); @unlink(Yii::getAlias('@frontend') . '/web/file/' . $model->namafile); $model->delete(); return $this->redirect(['index']); } |
5. public function actionDeleteUpload : Untuk menghapus file di dalam FileInput
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
public function actionDeleteUpload() { Yii::$app->response->format = \yii\web\Response::FORMAT_JSON; $keys = Yii::$app->request->post('key'); $key = explode(' ', $keys); $model = File::find()->where([ 'id' => $key[1], //'create_id' => Yii::$app->user->id ])->one(); if ($key[0] == 'namafile') { @unlink(Yii::getAlias('@frontend') . '/web/file/' . $model->namafile); $model->namafile = NULL; $model->save(false); } return []; } |
Tambahkan function findModel dan jangan lupa untuk use extension yang diperlukan, sehingga FileController.php menjadi seperti ini :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 |
<?php namespace frontend\controllers; use Yii; use common\models\File; use yii\web\Controller; use yii\web\NotFoundHttpException; use yii\filters\VerbFilter; use yii\web\UploadedFile; /** * FileController implements the CRUD actions for File model. */ class FileController extends Controller { public function actionIndex(){ $files = File::find()->all(); return $this->render('index',[ 'files' => $files, ]); } public function actionCreate() { $model = new File(); if ($model->load(Yii::$app->request->post())) { $model->namafile = UploadedFile::getInstance($model,'namafile'); if($model->namafile){ $file = $model->namafile->name; if ($model->namafile->saveAs(Yii::getAlias('@frontend').'/web/file/'.$file)){ $model->namafile = $file; } } $model->save(); return $this->redirect(['index']); } else { return $this->render('create', [ 'model' => $model, ]); } } public function actionUpdate($id) { $model = $this->findModel($id); $old_file = $model->namafile; if ($model->load(Yii::$app->request->post())) { $model->namafile = UploadedFile::getInstance($model,'namafile'); if($model->namafile){ $file = $model->namafile->name; if ($model->namafile->saveAs(Yii::getAlias('@frontend').'/web/file/'.$file)){ $model->namafile = $file; } } if (empty($model->namafile)){ $model->namafile = $old_file; } $model->save(); return $this->redirect(['index']); } else { return $this->render('update', [ 'model' => $model, ]); } } public function actionDelete($id) { $model = $this->findModel($id); @unlink(Yii::getAlias('@frontend') . '/web/file/' . $model->namafile); $model->delete(); return $this->redirect(['index']); } public function actionDeleteUpload() { Yii::$app->response->format = \yii\web\Response::FORMAT_JSON; $keys = Yii::$app->request->post('key'); $key = explode(' ', $keys); $model = File::find()->where([ 'id' => $key[1], //'create_id' => Yii::$app->user->id ])->one(); if ($key[0] == 'namafile') { @unlink(Yii::getAlias('@frontend') . '/web/file/' . $model->namafile); $model->namafile = NULL; $model->save(false); } return []; } protected function findModel($id) { if (($model = File::findOne($id)) !== null) { return $model; } else { throw new NotFoundHttpException('The requested page does not exist.'); } } } ?> |
Buat folder baru bernama file di dalam folder views dan tambahkan file-file berikut
1. _form.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 |
<?php use yii\helpers\Html; use yii\helpers\ArrayHelper; use yii\widgets\ActiveForm; use common\models\File; use kartik\file\FileInput; use yii\helpers\Url; /* @var $this yii\web\View */ /* @var $model common\models\File */ /* @var $form yii\widgets\ActiveForm */ $url = Yii::$app->urlManagerFrontEnd->baseUrl; ?> <div class="Category-form"> <?php $form = ActiveForm::begin([ 'options'=>[ 'enctype'=>'multipart/form-data' ] ]); ?> <?php if (!$model->isNewRecord): ?> <?php $img = []; $json = []; if (!empty($model->namafile)){ $img[] = Html::img($url.'/file/'.$model->namafile); $json[] = [ 'caption'=>$model->namafile, Url::to(['/file/delete-upload']), 'key' => 'namafile '. $model->id, ]; } ?> <?= $form->field($model, 'namafile')->widget(FileInput::className(),[ 'options' => ['accept' => ''], 'pluginOptions' => [ 'showRemove'=> false, 'showUpload' => false, 'showCancel' => false, 'overwriteInitial' => false, 'initialPreviewConfig' => $json, 'previewFileType' => 'image', 'initialPreview' => $img, 'uploadAsync'=> true, 'maxFileSize' => 3*1024*1024, 'deleteUrl' => Url::to(['/file/delete-upload']), 'allowedExtensions' => ['jpg','png','jpeg'], ] ])?> <?php else : ?> <?= $form->field($model, 'namafile')->widget(FileInput::classname(), [ 'options' => ['accept' => ''], 'pluginOptions' => [ 'showUpload' => false, ] ]); ?> <?php endif; ?> <div class="form-group"> <?= Html::submitButton($model->isNewRecord ? Yii::t('app', '<strong>Create</strong>') : Yii::t('app', '<strong>Update</strong>'), ['class' => $model->isNewRecord ? 'btn btn-success btn-slideright btn-md rounded' : 'btn btn-primary btn-slideright btn-md rounded']) ?> </div> <?php ActiveForm::end(); ?> </div> |
2. create.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
<?php use yii\helpers\Url; use yii\helpers\Html; $this->title = 'Create File'; $this->params['breadcrumbs'][] = $this->title; ?> <div class="body-content animated fadeIn"> <div class="row"> <div class="col-sm-12 col-md-12"> <!-- Start Summernote 5 WYSIWYG Editor --> <div class="panel rounded shadow"> <div class="panel-heading"> <div class="pull-left"> <h3 class="panel-title"><span class="icon"><i class="glyphicon glyphicon-list-alt"></i></span> Upload File</h3> </div> <div class="clearfix"></div> </div><!-- /.panel-heading --> <div class="panel-body"> <?= $this->render('_form',['model'=>$model]);?> </div><!-- /.panel-body --> </div><!-- /.panel --> <!--/ End Summernote 5 WYSIWYG Editor --> </div> </div><!-- /.row --> </div> |
3. index.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 |
<?php use yii\helpers\Url; use yii\helpers\Html; $this->title = 'File'; $this->params['breadcrumbs'][] = $this->title; $no = 1; ?> <div class="body-content animated fadeIn"> <div class="row"> <div class="col-sm-12 col-md-12"> <!-- Start Summernote 5 WYSIWYG Editor --> <div class="panel rounded shadow"> <div class="panel-heading"> <div class="pull-left"> <h3 class="panel-title"><span class="icon"><i class="glyphicon glyphicon-list-alt"></i></span> Files</h3> </div> <div class="clearfix"></div> </div><!-- /.panel-heading --> <div class="panel-body"> <div class="table-responsive rounded mb-20 col-sm-12"> <a href="<?= Url::to(['create']); ?>" class="btn btn-success btn-md rounded"><span class="icon"><i class="fa fa-plus"></i> </span><strong>Upload File</strong></a> <br /><br /> <table id="tour-16" class="table table-striped table-theme"> <thead> <tr> <th class="text-center border-right">No</th> <th class="text-center">File</th> </tr> </thead> <tbody> <?php if($files):?> <?php foreach($files as $file):?> <tr> <td class="text-center border-right"><?= $no; ?></td> <td class="text-center"> <?php if(!empty($file->namafile)):?> <img src="<?= Yii::$app->urlManagerFrontEnd->baseUrl.'/file/'.$file->namafile;?>"/> <?php endif;?> </td> <td class="text-center"> <a data-toggle="tooltip" title="update" href="<?= Url::to(['update','id'=>$file->id]); ?>" class="btn btn-primary btn-xs rounded"><strong>Update</strong></a> <a data-toggle="tooltip" title="delete" href="<?= Url::to(['delete','id'=>$file->id]); ?>" class="btn btn-danger btn-xs rounded"><strong>Delete</strong></a> </td> <?php $no++;?> </tr> <?php endforeach;?> <?php else : ?> <tr> <td colspan=6 class="text-center text-green"><strong>Tidak ada file yang telah ditambahkan</strong></td> </tr> <?php endif;?> </tbody> </table> </div> </div><!-- /.panel-body --> </div><!-- /.panel --> <!--/ End Summernote 5 WYSIWYG Editor --> </div> </div><!-- /.row --> </div> |
4. update.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
<?php use yii\helpers\Url; use yii\helpers\Html; $this->title = 'Update File'; $this->params['breadcrumbs'][] = $this->title; ?> <div class="body-content animated fadeIn"> <div class="row"> <div class="col-sm-12 col-md-12"> <!-- Start Summernote 5 WYSIWYG Editor --> <div class="panel rounded shadow"> <div class="panel-heading"> <div class="pull-left"> <h3 class="panel-title"><span class="icon"><i class="glyphicon glyphicon-list-alt"></i></span> Update File</h3> </div> <div class="clearfix"></div> </div><!-- /.panel-heading --> <div class="panel-body"> <?= $this->render('_form',['model'=>$model]);?> </div><!-- /.panel-body --> </div><!-- /.panel --> <!--/ End Summernote 5 WYSIWYG Editor --> </div> </div><!-- /.row --> </div> |
Langkah 4 : Membuat folder untuk menampung File
Buatlah folder untuk menampung file yang diupload. Pada contoh ini file akan disimpan di folder frontend/web/file.
Testing
Kita coba untuk mengupload sebuah file : http://localhost/yii2advanced/frontend/web/index.php?r=file/create
Menu index :
Tekan Update untuk mengganti file dan tekan Delete untuk menghapus file.
Apabila ingin membatasi hanya file gambar saja yang bisa diupload, atau file pdf saja misalnya, maka perlu menambahkan keterangan berikut di options :
Hanya accept file gambar saja :
1 |
'options' => ['accept' => 'image/*'], |
Hanya accept file pdf saja :
1 |
'options' => ['accept' => 'pdf'], |
Pada controller terdapat function DeleteUpload. Function ini berguna untuk menghapus file ketika ada di layar FileInput ketika melakukan Update data (tombol trash bin warna merah) :
Untuk dokumentasi Widget FileUpload : http://demos.krajee.com/widget-details/fileinput