Yii2 implements ajax image Upload plug-in usage ,. Yii2 implements ajax image Upload plug-in usage. this example describes how Yii2 implements ajax image Upload plug-in usage. For your reference, please download the mdmso Yii2 ajax image Upload plug-in,
This example describes how to use the Yii2 ajax image Upload plug-in. We will share this with you for your reference. The details are as follows:
Download the mdmsoft/yii2-upload-file. plug-in first.
The code is as follows:
public function actionCreate(){ $model = new DynamicModel([ 'nama', 'file_id' ]); // behavior untuk upload file $model->attachBehavior('upload', [ 'class' => 'mdm\upload\UploadBehavior', 'attribute' => 'file', 'savedAttribute' => 'file_id' // coresponding with $model->file_id ]); // rule untuk model $model->addRule('nama', 'string') ->addRule('file', 'file', ['extensions' => 'jpg']); if ($model->load(Yii::$app->request->post()) && $model->validate()) { if ($model->saveUploadedFile() !== false) { Yii::$app->session->setFlash('success', 'Upload Sukses'); } } return $this->render('upload',['model' => $model]);}
Then in view upload. php
<?phpuse yii\helpers\Html;use yii\widgets\ActiveForm;/* @var $this yii\web\View */?> <?php $form = ActiveForm::begin([ 'options' => [ 'enctype' => 'multipart/form-data'] ]); ?> <?= $form->field($model, 'nama'); ?> <?= $form->field($model, 'file')->fileInput(); ?> <?php if ($model->file_id): ?>
<?= Html::img(['/file', 'id' => $model->file_id]) ?>
<?php endif; ?> <?= Html::submitButton('Submit', ['class' => 'btn btn-primary']) ?>
<?php ActiveForm::end(); ?>