How to upload a file to directory in yii2?

后端 未结 6 1193
再見小時候
再見小時候 2020-12-09 08:57

i have an ActiveForm, and i want to add a field where the user can upload their photos. the problem is that i don\'t have an attribute for the image in the users table and e

6条回答
  •  不思量自难忘°
    2020-12-09 09:17

    Follow the official documentation

    https://github.com/yiisoft/yii2/blob/master/docs/guide/input-file-upload.md

    Form Model

    namespace app\models;
    
    use yii\base\Model;
    use yii\web\UploadedFile;
    
    /**
    * UploadForm is the model behind the upload form.
    */
    class UploadForm extends Model
    {
    /**
     * @var UploadedFile|Null file attribute
     */
    public $file;
    
    /**
     * @return array the validation rules.
     */
    public function rules()
    {
        return [
            [['file'], 'file'],
        ];
    }
    }
    ?>
    

    Form View

     ['enctype' => 'multipart/form-data']]); ?>
    
    field($model, 'file')->fileInput() ?>
    
    
    
    
    

    Controller

    Now create the controller that connects form and model together:

    request->isPost) {
            $model->file = UploadedFile::getInstance($model, 'file');
    
            if ($model->validate()) {                
                $model->file->saveAs('uploads/' . $model->file->baseName . '.' . $model->file->extension);
            }
        }
    
        return $this->render('upload', ['model' => $model]);
    }
    }
    ?>
    

    Instead of model->load(...) we are using UploadedFile::getInstance(...). [[\yii\web\UploadedFile|UploadedFile]] does not run the model validation. It only provides information about the uploaded file. Therefore, you need to run validation manually via $model->validate(). This triggers the [[yii\validators\FileValidator|FileValidator]] that expects a file:

     $file instanceof UploadedFile || $file->error == UPLOAD_ERR_NO_FILE //in code framework
    

    If validation is successful, then we're saving the file:

     $model->file->saveAs('uploads/' . $model->file->baseName . '.' . $model->file->extension);
    

    If you're using "basic" application template then folder uploads should be created under web.

    That's it. Load the page and try uploading. Uplaods should end up in basic/web/uploads.

提交回复
热议问题