error yii2 upload Call to a member function saveAs() on null

被刻印的时光 ゝ 提交于 2020-01-15 10:43:08

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!