2016-12-27 63 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的最佳方式。