问题
I am new programmer world and ask for your help guys, I have error "Call to a member function saveAs() on null"
This code in models
[['file'],'file'],
this code in controllers
$docfileload = $model->docname; $model->file = UploadedFile::getinstance($model,'file'); $model->file->saveAs('uploads/'.$docfileload.'.'.$model->file->extension); $model->save(); //save path in db $model->docfile = 'uploads/'.$docfileload.'.'.$model->file->extension;
this code in _form
<?= $form->field($model,'file')->fileinput(); ?>
after I used getInstanceByName like @bluehipy told me I have a new issue look to the pic
enter image description here
回答1:
Try this one :
$model->file=UploadedFile::getInstance($model,'file');
$model->pic=$model->file->extension; // pic is a field in database varchar(20)
$model->save(false) ;
$ImageName=$model->id;
if (!file_exists('uploads/'.$ImageName)) {
mkdir('uploads/'.$ImageName, 0777, true);
}
$model->file->saveAs( 'uploads/'.$ImageName.'/'.$ImageName.'.'.$model-
>file->extension );
`
回答2:
UploadedFile::getinstance
returns an array
of files. Use getInstanceByName
or UploadedFile::getinstance($model, 'file')[0]
.
来源:https://stackoverflow.com/questions/45902581/error-yii2-upload-call-to-a-member-function-saveas-on-null