jodit Yii2 изменение имени файла при загрузке - PullRequest
0 голосов
/ 09 февраля 2020

Я пытаюсь настроить Jodit WYSIWYG, и я нахожу их документацию довольно запутанной. Я ищу способ изменить имя файла при загрузке.

причина: если я загружу имя файла с тем же именем в каталог root, он заменит старый файл.

Итак, как изменение имени файла при загрузке для отмены заменяет файл старого имени.

здесь процедура загрузки файлов изображения 3 1.jpg, 2.jpg, 3.jpg

, когда в режиме отладки имя файла находится в

$ files = $ _FILES [$ source-> defaultFilesKey];

в функции

public function move(Config $source) {
        $files = $_FILES[$source->defaultFilesKey];
        /**
         * @var $output File[]
         */
        $output = [];

        try {
            if (isset($files) and is_array($files) and isset($files['name']) and is_array($files['name']) and count($files['name'])) {
                foreach ($files['name'] as $i => $file) {
                    if ($files['error'][$i]) {
                        throw new \Exception(isset(Helper::$upload_errors[$files['error'][$i]]) ? Helper::$upload_errors[$files['error'][$i]] : 'Error', $files['error'][$i]);
                    }

                    $path = $source->getPath();
                    $tmp_name = $files['tmp_name'][$i];
                    $new_path = $path . Helper::makeSafe($files['name'][$i]);
                    if (!move_uploaded_file($tmp_name, $new_path)) {
                        if (!is_writable($path)) {
                            throw new \Exception('Destination directory is not writeble', Consts::ERROR_CODE_IS_NOT_WRITEBLE);
                        }

                        throw new \Exception('No files have been uploaded', Consts::ERROR_CODE_NO_FILES_UPLOADED);
                    }
                    $file = new File($new_path);

                    try {
                        $this->accessControl->checkPermission($this->getUserRole(), $this->action, $source->getRoot(), pathinfo($file->getPath(), PATHINFO_EXTENSION));
                    } catch (\Exception $e) {
                        $file->remove();
                        throw $e;
                    }

                    if (!$file->isGoodFile($source)) {
                        $file->remove();
                        throw new \Exception('File type is not in white list', Consts::ERROR_CODE_FORBIDDEN);
                    }

                    if ($source->maxFileSize and $file->getSize() > Helper::convertToBytes($source->maxFileSize)) {
                        $file->remove();
                        throw new \Exception('File size exceeds the allowable', Consts::ERROR_CODE_FORBIDDEN);
                    }

                    $output[] = $file;
                }
            }
        } catch (\Exception $e) {
            foreach ($output as $file) {
                $file->remove();
            }
            throw $e;
        }

        return $output;
    }

, поэтому $ file сохраняет имя файла в массиве

enter image description here

Мне нужно указывать $ fiels и изменять значение массива ['name']. но я не знаю, как его изменить.

ОБНОВЛЕНИЕ после того, как я попробовал, я получил решение, использующее foreach statment для l oop $ files ['name'].

public function move(Config $source) {
        $files = $_FILES[$source->defaultFilesKey];
        foreach ($files['name'] as $i => $file) {
            $files['name'][$i] =  round(microtime(true)).($files['name'][$i]);
            }

            /**
             * @var $output File[]
             */
            $output = [];

             .
             .
             .
        }

1 Ответ

0 голосов
/ 13 февраля 2020

Вы можете использовать saveas метод php для загрузки нового переименованного файла:

//New name for file
$newName        = date("m-d-Y-h-i-s", time())."-".$filename.'.'.$ext;

$model->files  = CUploadedFile::getInstance($model,'files');



  $fullFileSource = Yii::getPathOfAlias('webroot').'/upload/'.$newName;
  $model->files->saveAs($fullFileSource);
...