phplaravelfile-manager

(edsdk / flmngr) Uploading Image has no naming convention or rules


I am using the edsdk/flmngr library for a personal php/laravel project. However, I want to add the following constraint:

When a user is uploading a file into the gallery from the CMS, the file name should be cleared of all symbols and weird characters as well as empty spaces. By default I know that it removes some of the symbols, but it definetely does not remove spaces.

e.g. Top Three Countries To Study.jpg should be renamed to TopThreeCountriesToStudy.jpg but it does not.

Any hints on which files to change or how to accomplish this is much appreciated.

I tried editing the fixFileName method in the Utils.php class so that the name that end up being used has no spaces, but for some reason it does not seem to work.

  public static function fixFileName($name) {
    $newName = '';
    for ($i = 0; $i < strlen($name); $i++) {
      $ch = substr($name, $i, 1);
      if (strpos(Utils::PROHIBITED_SYMBOLS, $ch) !== FALSE) {
        $ch = '_';
      }
      $newName = $newName . $ch;
      $newName = Str::replace(" ", "", $newName); //THIS IS THE LINE I ADDED
    }
    return $newName;
  }

Solution

  • You can pass a listener hookBeforeUpload into Flmngr and do whatever you want with files and their names. You can filter files or change their names.

    So please do not edit the code of the Flmngr library (when you update it, all the changes will be lost), pass this option into a set of parameters you pass into Flmngr.

    Full CodePen example - but with another type of file name replacements.

    Your case:

    hookBeforeUpload: (files) => {
        for (let i=0; i<files.length; i++) {
          
          // This is a File object. Set a new name for the file like "1.png",
          // where "1" is a number of the file, and "png" - its original extension.
          let file = files[i];
          
          let ext = null;
          let indexDot = file.name.lastIndexOf(".");
          if (indexDot > -1)
            ext = file.name.substr(indexDot + 1);
    
          let newFileName = file.name.substr(0, indexDot).replace(
    
               // Replace all spaces with empty strings by regexp
               / /g, 
               "" 
    
          ) + (ext === null ? "" : ("." + ext));
          let blob = file.slice(0, file.size, file.type);
          files[i] = new File([blob], newFileName, {type: file.type});
        }
    }