yii中的文件上传以及验证码

这次我把文件上传以及验证码写在一起,大家可以参考一下

说明:(这里是在Advanced前台中)

首先在控制器(controller)层:

<?

namespace frontend\controllers;


use Yii;
use yii\web\Controller;

use frontend\models\UploadForm;
use yii\web\UploadedFile;
use yii\captcha\Captcha;

class HelloController extends Controller {

  public function actionUpload()
    {
      /*  $path = \YII::getAlias("@webroot"); //路径,默认在web下
        echo $path;die();*/
        $model = new UploadForm();

      if ( $model->load(\YII::$app->request->post())&&\Yii::$app->request->isPost){
          $model->file = UploadedFile::getInstance($model, 'file');
          if ( $model->validate()) {   
           $path = \YII::getAlias("@webroot");              
            $model->file->saveAs($path."/uploads/".$model->file->baseName.".".$model->file->extension);//在frontend中web文件夹下建立一个uplodes
            Yii::$app->session->addFlash("success","uplode success");//上传成功可以提示上面的uplode success文字提示
          }
      }

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

}

在models中

namespace frontend\models;

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

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

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

在 view中

<?php
use yii\widgets\ActiveForm;
use yii\captcha\Captcha;
$form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]); ?>

<?= $form->field($model, 'file')->fileInput() ?>
<?= $form->field($model, 'verifyCode')->widget(Captcha::className(), [
'template' => '<div class="row"><div class="col-lg-3">{image}</div><div class="col-lg-6">{input}</div></div>'
]) ?>
<button>Submit</button>

<?php ActiveForm::end(); ?>


?>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值