Working with Yii framework 2.0 I want to be able to upload multiple files. Following the Yii 2 documentation , under the Upload Multiple Files subsection, I have the following model.
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; } } }
Below is my opinion.
<?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() ?>
In my controller, I have the following code snippet.
if (Yii::$app->request->isPost) { $model->attachment_file = UploadedFile::getInstances($model, 'attachment_file'); if ($model->upload()) { die();
With all the code above, I expect that I can select multiple files with one element of the input file. But that is not what I expect. When I select several files with the same input file element and click "Submit", I saw only the last selected file. Therefore, I have doubts about what I'm doing. Did I do something wrong? Or do I need to add an input file element several times, one input file element for one uploaded file?
php file-upload yii2
O connor
source share