yii2.0图片上传

Posted HongEternity

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了yii2.0图片上传相关的知识,希望对你有一定的参考价值。

<?php
namespace frontend\controllers;

use Yii;
use frontend\models\UploadForm;
use yii\web\UploadedFile;


class UploadController extends \yii\web\Controller
{
    public function actionUpload()
    {
     //实例化model
      $model = new UploadForm();
     //接值
        if (Yii::$app->request->isPost) {
            $model->file = UploadedFile::getInstance($model, ‘file‘);
        //验证
       if ($model->file && $model->validate()) {
                $fileName = date("Ymd H:i:s").$model->file->baseName . "." .$model->file->extension;
                 //图片的路径
                 $dir = ‘uploads‘."/". $fileName;
                //保存
                $model->file->saveAs($dir);
                //$model->file->saveAs(‘uploads/‘ . $model->file->baseName . ‘.‘ . $model->file->extension);

            }
        }

        return $this->render(‘upload‘, [‘model‘ => $model]);
    }
}

model层uploadfrom.php
<?php


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 file attribute
     */
    public $file;

    /**
     * @return array the validation rules.
     */
    public function rules()
    {
        return [
            [[‘file‘],‘file‘]
        ];
    }
}
view里面upload.php

<?php
use yii\widgets\ActiveForm;
use yii\helpers\html;
?>

<?php $form = ActiveForm::begin([‘options‘ => [‘enctype‘ => ‘multipart/form-data‘]]) ?>

<?= $form->field($model,‘file‘)->fileInput() ?>

    <button>提交</button>

<?php ActiveForm::end() ?>


<?= Html::img(‘@web/uploads/1.jpg‘, [‘alt‘ => ‘My logo‘]) ?>


以上是关于yii2.0图片上传的主要内容,如果未能解决你的问题,请参考以下文章

yii2.0上传图片

yii2.0单文件上传和多文件上传

Yii2.0 多文件上传

yii2-Ueditor百度编辑器

新手 想问下,上传图片到FastDfs后,如何在该虚拟机下找到上传的图片

怎样向网站上传图片