'Problems getting instance of UploadedFile in Yii2

I tried to upload a file to a server using UploadedFile class, but I can't get an Instance. In my Model:

public $arch;
public function rules() {
    return [[['arch'], 'file']];
}

Before $model->arch = file_xxxx.jpg

Controller:

$model->arch = UploadedFile::getInstance($model, 'arch');

After this $model->arch is NULL

View:

$form = ActiveForm::begin(
    ['id' => 'contact-form'],
    ['options' => ['enctype' => 'multipart/form-data']]
);
print $form->field($model, 'arch')->fileInput()->label(false);


Solution 1:[1]

You can try to get a file as follows:

// View
<?= $form->field($model, 'arch')->fileInput(); ?>

// Controller
$model->arch = UploadedFile::getInstanceByName('arch');

getInstanceByName() - returns an uploaded file according to the given file input name.

Complete yii2 Uploading Files guide.

Solution 2:[2]

In my case, it happened because I forgot to add

'options' => ['enctype' => 'multipart/form-data']

to ActiveForm options.

Solution 3:[3]

I have encountered a similar problem and found that missing "s",

$names = UploadedFile::getInstances($model, 'filename');

and it works.

Solution 4:[4]

Just hit that issue and it was my upload size in PHP ini file. It was 2MB and file was 2MB. I extended it to 200MB and all worked!

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 nicolascolman
Solution 3 MikeH
Solution 4 Stefano Mtangoo