V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
River1
V2EX  ›  程序员

yii2.0 使用插件实现一个简单的上传功能

  •  
  •   River1 · 2015-09-22 10:25:21 +08:00 · 1517 次点击
    这是一个创建于 3194 天前的主题,其中的信息可能已经有所发展或是发生改变。
    这个教程需要下载扩展( extension ) mdmsoft/yii2-upload-file.
    
    首先创建一个控制器
    
    // in controller
    public function actionCreate()
    {
        $model = new DynamicModel([
            'nama', 'file_id'
            ]);
    
        // behavior untuk upload file
        $model->attachBehavior('upload', [
            'class' => 'mdm\upload\UploadBehavior',
            '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]);
    }
    然后创建一个 upload.php 的视图
    <?php
    use yii\helpers\Html;
    
    use yii\widgets\ActiveForm;
    
    /* @var $this yii\web\View */
    
    ?>
    
    <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 class="form-group">
    
                <?= Html::img(['/file', 'id' => $model->file_id]) ?>
    
            </div>
    
        <?php endif; ?>
    
    
    
        <div class="form-group">
    
            <?= Html::submitButton('Submit', ['class' => 'btn btn-primary']) ?>
    
        </div>
    
        <?php ActiveForm::end(); ?>
    
    </div>
    
    目前尚无回复
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   2975 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 12:15 · PVG 20:15 · LAX 05:15 · JFK 08:15
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.