Yii2.0 文件上传

UploadForm.php

namespace backend\models;

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

class UploadForm extends Model
{
    /**
     * @var UploadedFile
     */
    public $file;
    public function rules()
    {
        return [
            [['file'], 'file', 'skipOnEmpty' => false, 'extensions' => 'png, jpg'],
        ];
    }

    public function upload()
    {
        if ($this->validate()) {
            $this->file->saveAs('uploads/' . $this->file->baseName . '.' . $this->file->extension);
            return true;
        } else {
            return false;
        }
    }
}

***Controller:

显示上传页面

public function actionShow()
{
    $admin = new AdminWechat;
    $id = Yii::$app->user->identity->id;
    $awechat = $admin->findOne(['user_id'=>$id]);

    $model = new UploadForm;
    return $this->render('upload', [
                'models' => $awechat,
                'model' => $model
            ]);
}
use backend\models\UploadForm;
use yii\web\UploadedFile;

/**
 *   文件上传
 *  图片的地址进行返回
 */
public function actionUpload ()
{
    $model = new UploadForm();
    $uploadSuccessPath = "";
    if (Yii::$app->request->isPost) {

        $model->file = UploadedFile::getInstance($model, "file");

        //文件上传存放的目录
        $adress = Url::to("@web/",true);
        $dir = "uploads/headimgs";

        if (!is_dir($dir)){
            mkdir($dir);
        }

        if ($model->validate()) {
            //文件名
            $fileName =   date("dMYHis").'.' . $model->file->extension;
            $dir = $dir."/". $fileName;
            $model->file->saveAs($dir);

            // 保存的路径
            $uploadSuccessPath = $adress.$dir;

            // 写入数据库
            $id = Yii::$app->user->identity->id;

            $admin = new AdminWechat;
            $awechat = $admin->findOne(['user_id'=>$id]);

            // 删除原来的头像

            preg_match('/\/([^\/]+\.[a-z]+)[^\/]*$/',$awechat->headimgurl,$match);
            unlink("uploads/headimgs" .$match[0]);

            $awechat->headimgurl = $uploadSuccessPath;

            if ($awechat->save()) {
                echo '<script>alert("修改成功!");window.history.back();</script>';
            }else{
                echo '<script>alert("修改失败,请检查图片格式,<br/>仅支持 jpg和png两种格式 !");window.history.back();</script>';
            }

        }
    }
    else{
        echo '<script>alert("非法上传方式!");window.history.back();</script>';
    }
}

view:

upload.php

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

<?php $form = ActiveForm::begin(['action' => ['config/upload'],'options' => ['enctype' => 'multipart/form-data']]) ?>
<?=  $form->field($models, 'id')->hiddenInput(['value'=>$model->id])->label('') ?>
<?= $form->field($models, 'file')->fileInput()->label('请选择图片:') ?>
<button>上传</button>
<?php ActiveForm::end() ?>



导航