How to upload multiple files using Yii framework 2.0

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(); // file is uploaded successfully return; } } 

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?

+9
php file-upload yii2
source share
2 answers

See what I tried: viewing the code

 <?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() ?> 

in the controller

  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 Model

 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], ]; } } 

This code works for me. Hope this works for you too.

+9
source share

Try this

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

0
source share

All Articles