FriendsOfCake / cakephp-upload

CakePHP: Handle file uploading sans ridiculous automagic
https://cakephp-upload.readthedocs.io/
MIT License
551 stars 255 forks source link

How to rename uploaded file #476

Closed anuj9196 closed 6 years ago

anuj9196 commented 6 years ago

I am having issue with name of files uploaded by user.

The file names contain space which is causing error in application functioning. I want to replace space with slug (- or _).

How can I do this in the plugin?

davidyell commented 6 years ago

Use the slug transformer?

https://github.com/FriendsOfCake/cakephp-upload/blob/master/src/File/Transformer/SlugTransformer.php

anuj9196 commented 6 years ago

How to use SlugTransformer in application? Do I need to play with source of of this plugin?

davidyell commented 6 years ago

The documentation has an example of using the transformer. http://cakephp-upload.readthedocs.io/en/latest/examples.html

anuj9196 commented 6 years ago
$this->addBehavior('Josegonzalez/Upload.Upload', [
            'video_file' => [
                'path' => 'webroot{DS}files{DS}{model}{DS}{field}{DS}{microtime}{DS}',
                'fields' => [
                    // if these fields or their defaults exist
                    // the values will be set.
                    'dir' => 'dir', // defaults to `dir`
                    //'size' => 'photo_size', // defaults to `size`
                    //'type' => 'photo_type', // defaults to `type`
                ],
                'transformer' => function ($table, $entity, $data, $field, $settings) {
                    $filename = pathinfo($data['name'], PATHINFO_FILENAME);
                    $filename = Inflector::slug($filename, '-');
                    $ext = pathinfo($data['name'], PATHINFO_EXTENSION);
                    if (!empty($ext)) {
                        $filename = $filename . '.' . $ext;
                    }
                    return [$data['tmp_name'] => strtolower($filename)];
                },
                'keepFilesOnDelete' => false,
            ],
        ]);

Is this how the loadBehaviour looks like in table?

anuj9196 commented 6 years ago

It worked. But how to pass this slugged file name to the video_file column. The file name in filesystem is slugged but video_file column still contains the name of file with space.

I tried slugging it in beforeSave but it also replace .mp4 to -mp4

anuj9196 commented 6 years ago

solved it using beforeSave()

public function beforeSave($event, $entity, $options)
    {
        $explode_ext = explode('.', $entity['video_file']);
        $file_name = str_replace('.'.end($explode_ext), '', $entity['video_file']);
        $file_name = Inflector::slug($file_name, '-');
        $entity['video_file'] = $file_name .'.'.end($explode_ext);
    }
davidyell commented 6 years ago

Great, good job 😄