4

I would like to rename a collection of uploaded files, but when I use addAllMediaFromRequest() I can't retrieve information from the files.

In this example; I need to know the file extension in order to rename the file.

$files = $post->addAllMediaFromRequest();

$files->each(function (FileAdder $file) {
    $file->usingFileName(Str::random(16) . '.jpg')  // What if it's a png?
         ->toMediaCollection();
});
apokryfos
  • 38,771
  • 9
  • 70
  • 114
Clément Baconnier
  • 5,718
  • 5
  • 29
  • 55

3 Answers3

0

To get a file extension within laravel:

$request->file('photo')->extension()

To create new file name:

        $newFileName = Str::random(20) .'.'.$request->file('photo')->extension();

don't forget to import Str class.

then you could rename the uploaded file before storing it easily

            $item->addMedia($request->photo)->usingFileName($newFileName)->toMediaCollection('photo');

code tested Laravel v9

Hussam Adil
  • 502
  • 7
  • 13
0

it can be done easly with toMediaCollection("media_collection_name")
in your code:

$files = $post->addAllMediaFromRequest(); 
$files->each(function (FileAdder $file) {
    $ext  = $file->extension();//this will get your file extension
    $file->usingFileName(Str::random(16) . '.'.$ext)
         ->toMediaCollection("media_collection_name");
});
Mohammed Ali
  • 1,117
  • 1
  • 16
  • 31
  • Thanks! But there no `extension` method in the [FileAdder class](https://github.com/spatie/laravel-medialibrary/blob/main/src/MediaCollections/FileAdder.php). It could be possible to add it with a macro though. But since I asked the question, there's a cleaner way to do it (see my answer) – Clément Baconnier Feb 28 '23 at 07:06
0

Since then, they have added the FileNamer class that allow to do what I was trying to achieve. You can can use your own class with the configuration.

FileNamer.php

namespace App;

use Spatie\MediaLibrary\Support\FileNamer\DefaultFileNamer;

class FileNamer extends DefaultFileNamer
{
    public function originalFileName(string $fileName): string
    {
        return \Str::random(16);
    }
}

media-library.php

/*
* This is the class that is responsible for naming generated files.
*/
'file_namer' => App\FileNamer::class,

StoreFilesController.php

$files = $post->addAllMediaFromRequest();

$files->each(fn (FileAdder $file) => $file->toMediaCollection());
Clément Baconnier
  • 5,718
  • 5
  • 29
  • 55