Nazil
Nazil

Reputation: 21

How to get the uploaded file in Controller which is uploaded through yii\helpers\Html::fileInput in Yii2

In my form I have used below code:

<?php echo Html::fileInput('imageFile', '', array('id' => 'contentForm_imageFile' )) ?>

and I tried to get the file in the controller with below code:

$newsModel->imageFile=UploadedFile::getInstance(Yii::$app->request->post('imageFile'), 'imageFile');
    $newsModel->imageFile->saveAs( 'uploads/'.$newsModel->file->basename.'.'.$newsModel->file->extension );

But I am getting this error when using above code to save the file:

Call to a member function saveAs() on null

since the API document of yii\web\UploadedFile says that:

getInstance() Returns an uploaded file for the given model attribute, The file should be uploaded using yii\widgets\ActiveField::fileInput().

So how can I get the uploaded file which is uploaded through yii\helpers\Html::fileInput?

Upvotes: 0

Views: 2780

Answers (3)

Insane Skull
Insane Skull

Reputation: 9368

You can get uploaded file without model using getInstanceByName()

$newsModel->imageFile = UploadedFile::getInstanceByName('imageFile');
$newsModel->imageFile->saveAs( 'uploads/'.$newsModel->file->basename.'.'.$newsModel->file->extension );

Upvotes: 3

Vitaly
Vitaly

Reputation: 1281

To form add 'enctype' => 'multipart/form-data'

In view:

<?= $form->field($model, 'imageFile')->fileInput(['id' => 'contentForm_imageFile']) ?>

Or

<?= Html::activeFileInput($model, 'imageFile', ['id' => 'contentForm_imageFile']) ?>

In Controller

$newsModel->imageFile = UploadedFile::getInstance($newsModel, 'imageFile');
$newsModel->imageFile->saveAs( 'uploads/'.$newsModel->file->basename.'.'.$newsModel->file->extension );

Upvotes: 0

marv255
marv255

Reputation: 818

Here is an official example for your situation: http://www.yiiframework.com/doc-2.0/guide-input-file-upload.html

Please double check your code:

  1. First of all is there an enctype="multipart/form-data" in your form tag?
  2. Next, see http://www.yiiframework.com/doc-2.0/yii-web-uploadedfile.html#getInstance()-detail for parameters of getInstance. It requires model instance as first parameter and field name as second parameter.
  3. Check that your server receives file that you send. Just var_dump($_FILES);

Upvotes: 1

Related Questions