ony 2015-06-29 09:58:03 54019次浏览 21条评论 54 28 0

创建一个 models/UploadForm.php:

namespace app\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’],
        ];
    }
}

视图文件

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

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

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

<button>Submit</button>

<?php ActiveForm::end() ?>

控制器

use app\models\UploadForm;
use yii\web\UploadedFile;



public function actionUpload()
{
    $model = new UploadForm();

    if (Yii::$app->request->isPost) {
        $model->file = UploadedFile::getInstance($model, ‘file’);

        if ($model->file && $model->validate()) {
            $model->file->saveAs(‘uploads/’ . $model->file->baseName . ‘.’ . $model->file->extension);
        }
    }

    return $this->render(‘upload’, ['model' => $model]);
}
觉得很赞
  • 评论于 2017-03-10 17:37 举报

    请问一下,这个上传不需要数据库??这个是不会保存在数据库中吗?

    1 条回复
    评论于 2017-03-14 09:56 回复

    数据库,你只需要保存图片的路径到数据库即可

您需要登录后才可以评论。登录 | 立即注册