本文实例讲述了Yii2实现ajax上传图片插件用法。分享给大家供大家参考,具体如下:
这里需要先下载 mdmsoft/yii2-upload-file.插件。
代码如下:
public function actionCreate() { $model = new DynamicModel([ 'nama', 'file_id' ]); // behavior untuk upload file $model->attachBehavior('upload', [ 'class' => 'mdmuploadUploadBehavior', '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
<?php use yiihelpersHtml; use yiiwidgetsActiveForm; /* @var $this yiiwebView */ ?> <div> <?php $form = ActiveForm::begin([ 'options' => [ 'enctype' => 'multipart/form-data'] ]); ?> <?= $form->field($model, 'nama'); ?> <?= $form->field($model, 'file')->fileInput(); ?> <?php if ($model->file_id): ?> <div> <?= Html::img(['/file', 'id' => $model->file_id]) ?> </div> <?php endif; ?> <div> <?= Html::submitButton('Submit', ['class' => 'btn btn-primary']) ?> </div> <?php ActiveForm::end(); ?> </div>
希望本文所述对大家基于Yii框架的PHP程序设计有所帮助。