Php 获取错误文件在yii2中不能为空
虽然上传了yii2中的文件,但仍然得到验证,配置文件Pic不能为空。我的代码如下。请帮我解决这个问题Php 获取错误文件在yii2中不能为空,php,yii2,Php,Yii2,虽然上传了yii2中的文件,但仍然得到验证,配置文件Pic不能为空。我的代码如下。请帮我解决这个问题 public function rules() { return [ [['profile_pic'], 'file'], [ ['profile_pic'], 'required', 'on' => 'update_pic']]; } 来自控制器 $model = new PostForm(['scenario' => 'update_pi
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;
}
正如@Bizley和@sm1979所评论的,您并没有按照需要处理文件上传 实际文件的接收方式与其他post参数不同,因此需要使用
UploadedFile::getInstance
获取文件实例并将其分配给模型中的profile\u 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;
}
最后,只是一个建议:阅读。阅读本文和是自己学习Yii2的最佳方式。你能发布其余的代码吗?调用此ruleRead添加了代码,因为你没有正确处理上传的文件。我不希望按照上述代码在模型中返回响应。请按照@Bizley的建议正确阅读该文档。使用
$model->load(Yii::$app->getRequest()->getBodyParams(),“”)
不会将上载的文件分配给模型。需要使用控制器中的UploadedFile::getInstance()
单独处理文件输入。所以我再次重申,请浏览@Bizley posted的链接,特别是标题为