【发布时间】:2015-10-06 16:41:44
【问题描述】:
Yii2 中的FileValidator 类是否只支持客户端验证?
我用代码写了文件上传系统:
在模型中:
public function rules() {
return [
[['allAllowedFileType'], 'safe'],
[['allAllowedFileType'], 'file',
'extensions'=>'jpg',
'mimeTypes' => 'image/jpeg'],
];
}
在控制器中:
public function actionCreate() {
$model = new File();
if ($model->load(Yii::$app->request->post())) {
// get the uploaded file instance. for multiple file uploads
// the following data will return an array
$image = UploadedFile::getInstance($model, 'allAllowedFileType');
// store the source file name
$model->name = $image->name;
$ext = end((explode(".", $image->name)));
// generate a unique file name
$avatar = Yii::$app->security->generateRandomString().".{$ext}";
$path = 'c:wamp/www/' . $avatar;
if($model->validate()&&$model->save(0)){
$image->saveAs($path);
return $this->redirect(['view', 'id'=>$model->id]);
} else {
// error in saving model
}
}
return $this->render('create', [
'model'=>$model,
]);
}
在视图中:
<?php
$form = ActiveForm::begin(['enableClientValidation' => true,
'options' => ['enctype' => 'multipart/form-data'] // important
]);
echo $form->field($model, "allAllowedFileType")->fileInput();
?>
加载无效文件(例如.php扩展的文件)时。
仅完成客户端验证。
一旦表格设置如下:
$form = ActiveForm::begin(['enableClientValidation' => false,
'options' => ['enctype' => 'multipart/form-data'] // important
]);
没有给出错误消息,文件不会被服务器端验证。
我也尝试将变量 ($model->allAllowedFileType) 设置如下:
$model->allAllowedFileType=$_FILES['File'];
我上传了无效文件,例如.exe扩展的文件)并执行验证功能,错误信息不会显示。$model->errors为空。
public function actionCreate() {
$model = new File();
if ($model->load(Yii::$app->request->post())) {
$image = UploadedFile::getInstance($model, 'allAllowedFileType');
...
$model->allAllowedFileType=$_FILES['File'];
if($model->validate()){
//save file
} else {
die(var_dump($model->errors));
}
}
return $this->render('create', [
'model'=>$model,
]);
}
【问题讨论】:
标签: php file validation yii2