Загрузка нескольких файлов yii2

Для мультизагрузки файлов нужно создать модель в каталоге models UploadForm.php

namespace app\models;

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

class UploadForm extends Model
{
    /**
     * @var UploadedFile[]
     */
    public $imageFiles;

    public function rules()
    {
        return [
            [['imageFiles'], 'file', 'skipOnEmpty' => false, 'extensions' => 'png, jpg', 'maxFiles' => 4,'checkExtensionByMimeType'=>false],
        ];
    }
    
    public function upload()
    {
        if ($this->validate()) { 
            foreach ($this->imageFiles as $file) {
				$filename=Yii::$app->getSecurity()->generateRandomString(15);
				// echo $filename;
                $file->saveAs('uploads/' . $filename . '.' . $file->extension);
            }
            return true;
        } else {
            return false;
        }
    }
}

Создадим функцию в контролере я создам функцию в контролере SiteController.php

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

        if (Yii::$app->request->isPost) {
            $model->imageFiles = UploadedFile::getInstances($model, 'imageFiles');
            if ($model->upload()) {
                // file is uploaded successfully
                return;
            }
        }

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

Далее создадим view upload в каталоге site

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

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

    <?= $form->field($model, 'imageFiles[]')->fileInput(['multiple' => true, 'accept' => 'image/*']) ?>

    <button>Submit</button>

<?php ActiveForm::end() ?>

Структура моих каталогов
2016-08-01_08-34-21

comments powered by HyperComments