Reputation: 21
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
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
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
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:
enctype="multipart/form-data"
in your form tag?var_dump($_FILES);
Upvotes: 1