在yii2 activeform中上传图片

时间:2019-01-31 12:32:14

标签: php image yii2 upload

我需要在我的项目文件夹中上传带有本地副本的简单图像:web / uploads / project + project_id + random_unique_key。我已经尝试过使用此代码,但是我想两个提交按钮之间存在冲突,我只希望第一个调用actionUpload()检查所选文件是否为图像,然后给我一个成功/错误消息,第二个调用actionCreate ()将模型保存在数据库中。 我的问题是,单击第二个按钮不执行任何操作,而单击第一个按钮则给出错误“图像不能为空白”。

视图/项目/创建

<?php $form = ActiveForm::begin(); ?>

<?= $form->field($model, 'title')->textInput(['maxlength' => true]) ?>

<?= $form->field($model, 'description')->textarea(['rows' => 6]) ?>

<?= $form->field($model, 'link')->textInput(['maxlength' => true]) ?>

<?= $form->field($model, 'image')->fileInput() ?>

<button>Upload</button>

<br></br>

<?= $form->field($model, 'is_deleted')->checkbox() ?>

<div class="form-group">
    <?= Html::submitButton('Save', ['class' => 'btn btn-success']) ?>
</div>

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

ProjectController

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

    if (Yii::$app->request->isPost) {
        $model->image = UploadedFile::getInstance($model, 'image');

        if ($model->validate()) {
            $model->image->saveAs('uploads/' . $model->image->baseName . '.' . $model->image->extension);
        }
    }

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

public function actionCreate()
{
    $model = new Project();

    if ($model->load(Yii::$app->request->post())){
        $model->setCreated_at();
        if($model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        }
    }

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

项目(模型)

public function rules()
{
    return [
        [['title', 'description', 'link', 'image', 'is_deleted'], 'required'],
        [['created_at'], 'safe'],
        [['is_deleted'], 'boolean'],
        [['title', 'description', 'link', 'image'], 'string', 'max' => 255],
    ];
}

谢谢。

2 个答案:

答案 0 :(得分:0)

我认为,在这种情况下,您的表单没有将文件发送到服务器。将enctype选项添加到您的表单:

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

答案 1 :(得分:-1)

单击按钮即可发出AJAX请求(可以使用Jquery)

$('form button').on('click', function(event){
    event.preventDefault();
    var form = document.forms[0];
    var formData = new FormData(form);

    if(formData.get('Project[image]')){ 
        $.ajax({
            method: "POST",
            url: '/upload',
            data: formData,
            success: function(error){
                if(error){
                     $(form).yiiActiveForm('updateAttribute', 'project-image', [error]);
                }
            }
        });
    }
})'

控制器

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

    if (Yii::$app->request->isAjax) {
        $model->image = UploadedFile::getInstance($model, 'image');

        if ($model->validate('image')) {
            $model->image->saveAs('uploads/' . $model->image->baseName . '.' . $model->image->extension);
        }
    }

    return $model->getFirstError('image');
}

规则

public function rules()
{
    return [
        [['title', 'description', 'link', 'is_deleted'], 'required'],
        [['created_at'], 'safe'],
        [['is_deleted'], 'boolean'],
        [['title', 'description', 'link'], 'string', 'max' => 255],
        [['image'], 'file', 'extensions' => 'png, jpg'],
    ];
}

如果你不想写自己的JS来初始化Ajax请求,您可以安装卡尔蒂克文件输入控件。

示例:

$form->field($model, 'image')->widget(FileInput::class,[
            'options' => [
                'accept' => 'image/*',
            ],
            'pluginOptions' => [
                'layoutTemplates' => [
                    'main1' =>'{preview}' .
                        '<div class="kv-upload-progress kv-hidden"></div><div class="clearfix"></div>' .
                        '<div class="input-group {class}">' .
                        '  {caption}' .
                        '  <div class="input-group-btn">' .
                        '    {upload}' .
                        '    {browse}' .
                        '  </div>' .
                        '</div>',
                    'main2' => '{preview}<div class="kv-upload-progress hide"></div>{upload}{browse}',
                ],
                'uploadUrl' => Url::to(['/upload']),
                'maxFileCount' => 1,
                'autoReplace' => true,
                'showPreview' => false,
                'showCaption' => true,
                'showRemove' => false,
                'showUpload' => true,
            ]
        ])

它将为您注册所有js代码以制作ajax。