fcq 2015-12-30 11:05:07 2783次浏览 0条回复 2 1 0

view试图

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

<?= $form->field($model, 'file[]')->fileInput(['multiple' => true])->label("") ?>
<?php ActiveForm::end() ?>  

model模型

<?php
namespace backend\models;

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

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

    public function rules()
    {
        return [
           [['file'], 'file', 'extensions' => 'jpg, png', 'mimeTypes' => 'image/jpeg, image/png', 'maxFiles' => 10],
        ];
    }

    // public function attributeLabels(){
    //     return [
    //         'file' => '商品缩略图上传',
    //     ];
    // }

}

控制器Controller

public function actionInsert(){

          $model = new UploadForm();

          if (Yii::$app->request->isPost) {

            $files = UploadedFile::getInstances($model, 'file');

            foreach ($files as $file) {
                $_model = new UploadForm();
                $_model->file = $file;

                if ($_model->file) {                    
                     if(!file_exists('uploads/')){
                       mkdir('uploads/',0777,true);
                    }
                    $_model->file->saveAs('uploads/' . $_model->file->baseName . '.' . $_model->file->extension);
                     
                } else {
                    foreach ($_model->getErrors('file') as $error) {
                        $model->addError('file', $error);
                     
                    }  
                }
            }
            
        }
      
        return $this->render('insert', ['model' => $model]);

    }
觉得很赞
    没有找到数据。
您需要登录后才可以回复。登录 | 立即注册