Annon
Annon

Reputation: 109

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);

Upvotes: 3

Views: 12445

Answers (5)

jai3232
jai3232

Reputation: 431

Check the upload error code. If the code number is 6, it is UPLOAD_ERR_NO_TMP_DIR meaning "Missing a temporary folder". Solution maybe ..:

  1. modify write access of temporary folder stated in upload_tmp_dir value of php.ini
  2. increase post_max_size in php.ini from 8M to a higher value
  3. increase upload_max_filesize in php.ini to a higher value

Upvotes: 0

Stefano Mtangoo
Stefano Mtangoo

Reputation: 6560

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!

Upvotes: 0

shrg18
shrg18

Reputation: 1

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

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

and it works.

Upvotes: 0

Oleksandr Pyrohov
Oleksandr Pyrohov

Reputation: 16226

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.

Upvotes: 5

user168508
user168508

Reputation: 31

In my case, it happened because I forgot to add

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

to ActiveForm options.

Upvotes: 3

Related Questions