Z
Z
ZaurK2018-04-30 18:39:29
Yii
ZaurK, 2018-04-30 18:39:29

Why does docx validation fail in yii2?

I can’t understand something, when uploading files, files with docx and txt extensions do not go through, the rest go through and are loaded. Moreover, the error occurs already during the download process. Help me understand what's wrong?
Controller:

<?php
namespace backend\controllers;

use Yii;
use yii\filters\AccessControl;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\web\Controller;
use backend\models\Fileload;
use yii\web\UploadedFile;

class FileloadController extends Controller
{
   /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
        'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'actions' => ['login', 'error'],
                        'allow' => true,
                    ],
                    [
                        'actions' => ['logout', 'index', 'update', 'view', 'create', 'delete'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
          
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }
    public function actionIndex()
    {
        $model = new Fileload();
        $dir = Yii::getAlias('@uploads') . '/files/';
    $name = 'price_titankbr';
    
        if (Yii::$app->request->isPost) {
            $model->loadFile = UploadedFile::getInstance($model, 'loadFile');
            $this->deleteIfExists($dir);
      if ($model->upload($dir, $name)) {
                // file is uploaded successfully
                return $this->redirect(['fileload/index']);
            }
        }

        return $this->render('upload', ['model' => $model]);
    }
  
  private function deleteIfExists($dir)
  {
    $files = scandir($dir);
    $files = array_slice($files,2);
    //print_r($files); exit;
    foreach($files as $fl){
      unlink($dir . $fl);
    }
    
  }
  
}

The form:
<?php
use yii\widgets\ActiveForm;
?>
<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]) ?>
    <?= $form->field($model, 'loadFile')->fileInput()->label('Файл прайс-листа') ?>
    <button>Загрузить</button>
<?php ActiveForm::end() ?>

Model:
<?php

namespace backend\models;

use Yii;
use yii\base\Model;
use yii\web\UploadedFile;

class Fileload extends Model
{
    /**
     * @var loadFile
     */
    public $loadFile;

  public $maxSize = 1024*1024*2;
  public $tooBig = 'Файл не должен превышать 2Мб';
  
    public function rules()
    {
        return [
            [['loadFile'], 'file', 'skipOnEmpty' => false, 'extensions' => ['pdf', 'doc', 'docx', 'txt',  'xls', 'xlsx'], 'maxSize' => $this->maxSize, 'tooBig' => $this->tooBig],
        ];
    }
    
    public function upload($dir, $name)
    {
        if ($this->validate()) {
            $this->loadFile->saveAs($dir . $name . '.' . $this->loadFile->extension);
      Yii::$app->session->setFlash('success', "Прайс-лист обновлен");
            return true;
        } else {
            return false;
        }
    }
}

Answer the question

In order to leave comments, you need to log in

[[+comments_count]] answer(s)
M
Maxim Timofeev, 2018-05-01
@ZaurK

The focus is this. There are two options for determining the file extension:
- by mime type
- cutting off the last dot
in yii by default the first one. But due to one reason or another, mime type works clumsily for you (well, or not as expected).
So make sure checkExtensionByMimeType => falsethis is enough for you. Or solve the issue with MimeType for docx and txt.
https://www.yiiframework.com/doc/api/2.0/yii-valid...
In summary - the problem is outside of yii2, dig the server or use the "head-on" method.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question