在yii2中获取错误文件不能为空

时间:2016-12-27 07:20:38

标签: php yii2

虽然在yii2上传文件,但仍然得到验证,配置文件Pic不能为空。我的代码如下规则。请帮我解决这个问题。

public function rules() {
    return [
        [['profile_pic'], 'file'],
        [ ['profile_pic'], 'required', 'on' => 'update_pic']];
}

来自控制器

$model = new PostForm(['scenario' => 'update_pic']);
if ($model->load(Yii::$app->getRequest()->getBodyParams(), '') && $model->validate()) {
    return ['status' => 1, 'message' => Yii::$app->params['messages']['post_success']];
} else {
    $model->validate();
    return $model;
}

1 个答案:

答案 0 :(得分:0)

就像@Bizley和@ sm1979评论一样,您无需处理文件上传,因为它需要完成。

实际文件的接收方式与其他邮件参数的接收方式不同,因此您需要使用UploadedFile::getInstance获取文件实例并将其分配给模型中的profile_pic属性。

在您的控制器中:

$model = new PostForm(['scenario' => 'update_pic']);
// We load the post params from the current request
if($model->load(Yii::$app->request->post())) {
    // We assign the file instance to profile_pic in your model.
    // We need to do this because the uploaded file is not a part of the
    // post params.
    $model->profile_pic = UploadedFile::getInstance($model, 'profile_pic')
    // We call a new upload method from your model. This method calls the
    // model's validate method and saves the uploaded file.
    // This is important because otherwise the uploaded file will be lost
    // as it is a temporary file and will be deleted later on.
    if($model->upload()) {
        return ['status' => 1, 'message' => Yii::$app->params['messages']['post_success']];
    }
}
return $model;

在你的模特中:

public function upload() {
    // We validate the model before doing anything else
    if($this->validate()) {
        // The model was validated so we can now save the uploaded file.
        // Note how we can get the baseName and extension from the 
        // uploaded file, so we can keep the same name and extension.
        $this->profile_pic->saveAs('uploads/' . $this->profile_pic->baseName . '.' . $this->profile_pic->extension);
        return true;
    }
    return false;
}

最后,只是一个建议:阅读The Definitive Guide to Yii 2.0。阅读本文和Yii2 API Documentation是自己学习Yii2的最佳方式。