可能使用插件更改CKFinder自动重命名格式?

问题描述:

我正在使用CKFinder 3.4 for PHP,我正在寻找一种方法来更改在上载服务器上已存在的文件时发生的自动重命名的格式。标准格式是将file.ext重命名为file(1).ext。我需要改变这file-1.ext.可能使用插件更改CKFinder自动重命名格式?

有可能在ckfinder的来源很轻松地改变功能:

/core/connector/php/vendor/cksource/ckfinder/src/CKSource/CKFinder/Filesystem/File/File.php

不过,我想,以避免更改源文件,因为它使得更新更难。

理想情况下,我想解决使用插件的问题,但BEFORE_COMMAND_FILE_UPLOAD事件似乎不包含(自动)重命名的文件名。

谁在那里谁曾经在类似的问题,并找到了解决方案吗?

我已经准备了一个小连接器插件,以您描述的方式重命名文件。不幸的是,我不能在没有小的破解的情况下实现这个结果:绑定一个闭包来访问一个私有对象属性。

想了解更多关于CKFinder 3 PHP Connector插件的信息,请看plugins docs

这里的插件,我希望你会发现它有用:

<?php 

namespace CKSource\CKFinder\Plugin\CustomAutorename; 

use CKSource\CKFinder\CKFinder; 
use CKSource\CKFinder\Event\BeforeCommandEvent; 
use CKSource\CKFinder\Event\CKFinderEvent; 
use CKSource\CKFinder\Filesystem\Folder\WorkingFolder; 
use CKSource\CKFinder\Plugin\PluginInterface; 
use Symfony\Component\EventDispatcher\EventSubscriberInterface; 
use Symfony\Component\HttpFoundation\File\UploadedFile; 

class CustomAutorename implements PluginInterface, EventSubscriberInterface 
{ 
    protected $app; 

    public function setContainer(CKFinder $app) 
    { 
     $this->app = $app; 
    } 

    public function getDefaultConfig() 
    { 
     return []; 
    } 

    public function onBeforeUpload(BeforeCommandEvent $event) 
    { 
     $request = $event->getRequest(); 

     /** @var UploadedFile $uploadedFile */ 
     $uploadedFile = $request->files->get('upload'); 

     /** @var WorkingFolder $workingFolder */ 
     $workingFolder = $this->app['working_folder']; 

     if ($uploadedFile) { 
      $uploadedFileName = $uploadedFile->getClientOriginalName(); 
      if (!$workingFolder->containsFile($uploadedFileName)) { 
       // File with this name doesn't exist, nothing to do here. 
       return; 
      } 

      $basename = pathinfo($uploadedFileName, PATHINFO_FILENAME); 
      $extension = pathinfo($uploadedFileName, PATHINFO_EXTENSION); 

      $i = 0; 

      // Increment the counter until there's no file named like this in current folder. 
      while (true) { 
       $i++; 
       $uploadedFileName = "{$basename}-{$i}.{$extension}"; 

       if (!$workingFolder->containsFile($uploadedFileName)) { 
        break; 
       } 
      } 

      // And here's the hack to make a private property accessible to set a new file name. 
      $setOriginalName = function (UploadedFile $file, $newFileName) { 
       $file->originalName = $newFileName; 
      }; 

      $setOriginalName = \Closure::bind($setOriginalName, null, $uploadedFile); 

      $setOriginalName($uploadedFile, $uploadedFileName); 
     } 
    } 

    public static function getSubscribedEvents() 
    { 
     return [CKFinderEvent::BEFORE_COMMAND_FILE_UPLOAD => 'onBeforeUpload']; 
    } 
} 
+0

非常感谢你,这正是我一直在寻找。 –