2016-12-27 103 views
0

中空白,但仍然验证Profile Pic不能为空。我的代码如下规则。请帮我解决这个问题。虽然在yii2中上传文件,但获取错误文件不能在yii2

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; 
} 
+0

你可以发布剩下的代码吗? – anon

+0

添加了调用此规则的代码 – bhavika

+1

请阅读http://www.yiiframework.com/doc-2.0/guide-input-file-upload.html,因为您没有正确处理上传的文件。 – Bizley

回答

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的最佳方式。