plank / laravel-mediable

Laravel-Mediable is a package for easily uploading and attaching media files to models with Laravel
MIT License
773 stars 101 forks source link

File gets renamed upon upload? #331

Closed hirisov closed 7 months ago

hirisov commented 1 year ago

Hello,

I to upload a file where the name is

something-.jpg

but in the media record it gets changed to something.jpg

Here is the request log:

[2023-09-22 19:47:13] local.INFO: array ( 'path' => 'path/to/something-.jpg', 'file' => Illuminate\Http\UploadedFile::__set_state(array( 'test' => false, 'originalName' => 'something-.jpg', 'mimeType' => 'image/jpeg', 'error' => 0, 'hashName' => NULL, )), )

and here is the created media record:

[2023-09-22 19:47:13] local.INFO: {"size":54172,"mime_type":"image\/jpeg","extension":"jpg","aggregate_type":"image","disk":"wasabi","directory":"_REMOVED_BUTCORRECT","filename":"something","updated_at":"2023-09-22T19:47:13.000000Z","created_at":"2023-09-22T19:47:13.000000Z","id":3281}

Anybody has idea please why this happens and how can I disable this behaviour?

EriBloo commented 1 year ago

While generating file name in MediaUploader upload method this method is being used:

    public static function sanitizeFileName(string $file, string $language = null): string
    {
        $language = $language ?: App::currentLocale();
        return trim(
            preg_replace(
                '/[^a-zA-Z0-9-_.%]+/',
                '-',
                Str::ascii($file, $language)
            ),
            '-'
        );
    }

which trims -.

If you really need to keep original filename either use ->beforeSave(fn (Media $media, SourceAdapterInterface $source) => $media->setAttribute('filename', $source->filename())) method to bring it back or add a separate column in the database to store it and call ->beforeSave(fn (Media $media, SourceAdapterInterface $source) => $media->setAttribute('original_filename', $source->filename())).