上传多个文件yii2

时间:2015-09-23 12:03:42

标签: file-upload yii2

告诉我我错在哪里,一切都在尝试

我的观看文件:

echo FileInput::widget([
 'model' => $model,
 'attribute' => 'files[]',
 'options' => ['multiple' => true]
]);

我也加了

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

用于表单元素的enctype选项

型号: 我添加两个变量作为属性:

public $files; // files instance
public $serialize; // set string which store the files

在规则中 序列化为字符串和文件:

[['files'], 'file', 'skipOnEmpty' => true, 'extensions' => 'gif, jpg, png, pdf, doc, docx', 'maxFiles' => 10],

和控制器操作:

public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post())) {
            $oldFiles = $model->serialize;
            $files = UploadedFile::getInstance($model, 'files');

            if($files === false){
              $model->serialize = $oldFiles;
            } else {
              $serialize = [];

              if($model->validate()){
                foreach($files as $file){
                  $ext = end((explode(".", $file)));
                  $filename = Yii::$app->security->generateRandomString().".{$ext}";
                  $serialize[] = $filename;
                  $file->saveAs(Yii::$app->basePath . '/web/image/' . $filename);
                }
              } else {

              }
              //print_r($model->getErrors()); die();
              $model->serialize = serialize($serialize);
            }
            $model->save();
            return $this->redirect(['view', 'id' => $model->news_id]);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

所以,$files是空的,为什么? 我在$_FILES数组

中得到“4”代码错误

1 个答案:

答案 0 :(得分:1)

多个文件应该是getInstances。

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