How to read HTML5 Multiple File Input from controller?

0 2
40
Viewed: 26 607 times
Version: 2.0
Category: How-tos
Written by: Kartik V Kartik V
Updated by: samdark samdark
Created: May 5, 2014
Updated: 7 years ago
  1. Problem Statement
  2. Solution

Problem Statement

Ok, so you have a HTML 5 file input markup on your view and you have enabled multiple attribute to true. You may also be using widgets based on HTML5 input like \kartik\widgets\FileInput. But when you read a file in Yii controller using CUploadedFile (Yii1) or UploadedFile (Yii2), you do not see a list of multiple files that you selected in your view, but only one row. Your HTML markup in your view would be something like this and you don't know why this is not working?

[html]
<input name="uploadFile" type="file" multiple="multiple">

Solution

You must configure the attribute name for HTML5 file input in ARRAY FORMAT for PHP to recognize it as an array of files. So here is how you achieve this as shown below (note the square brackets in the attribute naming):

For Yii 1.1
echo $form->fileInput($model, 'uploadFile[]', ['multiple' => true]);
For Yii 2
echo $form->field($model, 'uploadFile[]')->fileInput(['multiple' => true]);
For \kartik\widgets\FileInput (Yii 2)
echo $form->field($model, 'uploadFile[]')->widget(FileInput::classname(), [
    'options'=>['multiple' => true]
]);