如何使用Yii framework 2.0

时间:2015-08-26 02:46:29

标签: php file-upload yii2

使用Yii framework 2.0我希望能够上传多个文件。遵循Yii 2 documentation,在Upload Multiple Files小节下,我有以下模型。

class Newsletter extends \yii\db\ActiveRecord {
    public $attachment_file;

    public function rules()
    {
         return [
              [['attachment_file'], 'file', 'maxFiles' => 5],
         ];
    }

    public function upload() {

        if ($this->validate()) { 
            foreach ($this->attachment_file as $file) {
                echo '<pre>'; print_r($file); echo '</pre>';
            }
            return true;
        } else {
            return false;
        }
    }
}

以下是我的观点。

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

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

<?= $form->field($model, 'attachment_file[]')->fileInput(['multiple' => true,]) ?>

<button>Submit</button>

<?php ActiveForm::end() ?>

在我的控制器中,我有以下代码段。

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

使用上面的所有代码,我希望我可以选择带有一个输入文件元素的多个文件。但它不像我期望的那样。当我选择具有相同输入文件元素的多个文件并点击提交时,我只看到最后选择的文件。所以我开始怀疑我在做什么。我做错了什么吗?或者我需要多次添加输入文件元素,一个上传文件的输入文件元素是什么?

2 个答案:

答案 0 :(得分:9)

看看我尝试了什么: 查看代码

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

    <?= $form->field($uploadForm, 'files[]')->fileInput(['multiple' => true]) ?>

    <button class="btn btn-primary">Upload</button>
    <?php ActiveForm::end() ?>
控制器中的

    use yii\web\UploadedFile;
    use app\models\MultipleUploadForm;
    use app\models\ProductImage;
    .......
    function actionUploadImage() {
        $form = new MultipleUploadForm();

        if (Yii::$app->request->isPost) {
            $form->files = UploadedFile::getInstances($form, 'files');

            if ($form->files && $form->validate()) {
                foreach ($form->files as $file) {
                    $image = new ProductImage();
                    if ($image->save()) {
                        $file->saveAs($image->getPath());
                    }
                }

            }
        }

        return $this->render('uploadImage', [
            'uploadForm' => $form,
        ]);
    }

MultipleUploadForm模型

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

class MultipleUploadForm extends Model
{
    /**
     * @var UploadedFile[] files uploaded
     */
    public $files;

    /**
     * @return array the validation rules.
     */
    public function rules()
    {
        return [
        [['files'], 'file', 'extensions' => 'jpg', 'mimeTypes' => 'image/jpeg', 'maxFiles' => 10, 'skipOnEmpty' => false],
        ];
    }
}

这段代码对我有用。希望这也适合你。

答案 1 :(得分:-1)

尝试一下

<?=$form->field($formUpload, 'files[]')->fileInput(['multiple' => true])?>