在yii2上传多个图像

时间:2015-10-24 14:19:01

标签: php yii2

在yii2中上传多个图像不起作用!
视图:

 <?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]); ?>
<?= $form->field($uploadModel, 'imageFiles[]')->fileInput(['multiple' => 'multiple', 'accept' => 'image/*']) ?>
<div class="form-group">
    <?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>

控制器:

   $uploadModel = new \app\models\UploadForm();
    if (Yii::$app->request->isPost) {
        $uploadModel->imageFiles = \yii\web \UploadedFile::getInstance($uploadModel, 'imageFiles');
    if ($uploadModel->upload()) {
        echo 'successfully';
        return true;
            }else{
                 echo 'failed';
              }
    } else {
        return $this->render('create', [
            'model' => $model,
                    'uploadModel' => $uploadModel,
        ]);
    }

uploadModel:

 public $imageFiles;

public function rules() {
    return [
        [['imageFiles'], 'file', 'skipOnEmpty' => false, 'maxFiles' => 10, 'extensions' => 'png, jpg'],
    ];
}

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

我对kartik文件输入小部件有同样的问题!

1 个答案:

答案 0 :(得分:1)

要返回给定模型属性的所有上传文件,您必须调用

UploadedFile::getInstances($model, 'imageFiles'); 

的实例
UploadedFile::getInstance($model, 'imageFiles'); 

参考: Yii::UploadFile