Working with Yii framework 2.0 I want to be able to upload multiple files. Following Yii 2 documentation, under subsection Upload Multiple Files
I have the following model.
class Newsletter extends yiidbActiveRecord {
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 view.
<?php use yiiwidgetsActiveForm; ?>
<?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 I can select multiple files with one input file element. But it is not like what I expect. When I select multiple files with one same input file element and hit Submit I saw only the last selected file. So I start to have doubt about what I am doing. Did I do anything wrong? Or do I need to add input file element several times, one input file element for one uploading file?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…