Hello,
Is the FileValidator class in Yii2 only supports clientside validation ?
I written the file upload system with the use of code :
in model:
class File extends \yii\db\ActiveRecord {
.
.
.
public $allAllowedFileType;
public function rules() {
return [
[['allAllowedFileType'], 'safe'],
[['allAllowedFileType'], 'file',
'extensions'=>'jpg',
'mimeTypes' => 'image/jpeg'],
];
}
.
.
}
in controller:
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,
]);
}
in view :
<?php
use kartik\file\FileInput;
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use yii\helpers\ArrayHelper;
use yii\web\View;
use yii\helpers\Url;
?>
<div class="file-form">
<?php
$form = ActiveForm::begin(['enableClientValidation' => true,
'options' => ['enctype' => 'multipart/form-data'] // important
]);
echo $form->field($model, "allAllowedFileType")->fileInput();
?>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? Yii::t('app', 'Create') : Yii::t('app', 'Update'), ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
When a invalid file(for example file by .php extention) is loaded .
Only client-side validation is done.
Once the form is set as follows:
$form = ActiveForm::begin(['enableClientValidation' => false,
'options' => ['enctype' => 'multipart/form-data'] // important
]);
[color="#FF0000"]‘enableClientValidation’ => false[/color]
No error message is given and the files will not be Server side validated.
also i tried to set the variable ($model->allAllowedFileType) as follows :
$model->allAllowedFileType=$_FILES[‘File’];
I uploaded invalid file for example file by .exe extention) and execute validate function, the error message wont be displayed.and $model->errors is empty.
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,
]);
}