ckfinder / ckfinder-laravel-package

CKFinder 3 package for Laravel
Other
153 stars 86 forks source link

How to override default upload functionality #61

Open volosan opened 3 years ago

volosan commented 3 years ago

Hello! Thank you for your work!

I want to override default upload functionality. What exactly I want:

  1. Custom file paths and names. For example: /storage/app/public/uploads/media-library/<users_group_id>/<random_string>.jpg. Ok, 'baseUrl' and 'root' I can setup in /config/ckfinder.php. But how can I add 'users_group_id' (dynamic value) and random file name?
  2. Ideally I would like to use a disk.
  3. Make record in database for each uploaded file.
  4. Read files from custom folders.

My current solution: I've made a custom plugin for CKFinder and it works fine for me. In my plugin I am listening to event "CKFinderEvent::FILE_UPLOAD". But how I can prevent defaul upload functionality? Now my files are duplicates.

My code:

<?php

namespace CKSource\CKFinder\Plugin\UploadPlugin;

use App\Models\Account;
use App\Models\Media;
use CKSource\CKFinder\CKFinder;
use CKSource\CKFinder\Config;
use CKSource\CKFinder\Event\CKFinderEvent;
use CKSource\CKFinder\Event\FileUploadEvent;
use CKSource\CKFinder\Plugin\PluginInterface;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class UploadPlugin implements PluginInterface, EventSubscriberInterface
{
    protected $app;

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

    public function getDefaultConfig()
    {
        return [];
    }

    public function customAction(FileUploadEvent $event)
    {
        /* @var $account Account */
        $account = auth()->user();
        $businessId = $account->business->getKey();

        $uploadedFile = $event->getFile();

        $fileName = $businessId . DIRECTORY_SEPARATOR . Str::random(25) . '.' . $uploadedFile->getExtension();

        Storage::disk('media-library')->put($fileName, $uploadedFile->getContents());

        $path = Storage::disk('account')->path($fileName);
        $mime = mime_content_type($path);

        return Media::create(['path' => $path, 'name' => $fileName, 'type' => $mime]);
    }

    public static function getSubscribedEvents()
    {
        return [CKFinderEvent::FILE_UPLOAD => 'customAction'];
    }
}
volosan commented 3 years ago

I think, I have to override FileUploadcommand with my plugin, but I have no idea how.

bmlotek commented 1 year ago

Hello, do you still have the problem?