Pixelairport's avatar

Medialibrary with existing S3 files

I use Spatie Medialibrary for avatar images in my project. Now I want to add uploads. These are uploaded with transloadit. That means not with the normal laravel Storage or Spatie Medialibrary. But I want to connect the file after the upload with model item. Is that possible and makes this sense? I always get errors like "File not exist". Or should i use another workaround for this without medialibrary?

0 likes
6 replies
Pixelairport's avatar

Im a step closer...

$song->addMediaFromUrl($file)->toMediaCollection('song','songs');

This is what i do in my code, after upload the file with transloadit. The problem is, that the file is taken from s3 again and is duplicated into a second folder on s3. But the file is already there. Is there a way just to attach a file without uploading it?

1 like
Pixelairport's avatar

Ok. I use transloadit which copies the files to s3 and then i do another upload with spatie medialibrary, which use the path of the uploaded file and upload it a second time to right directory. For the start that works. If my project work, i will find another solution.

aviksdev's avatar

Did you find any solution to attach a file on s3 without uploading/copying it twice ?

noob_rider's avatar

I too have this issue, it's better if there's a method to attach files that already exist on the disk.

kamran86's avatar

Try this:

$song->addMediaFromUrl($file) ->toMediaCollection('song', 's3', 'path/to/custom/directory');

You File name might be same but your path to the file is not the same that's why its creating a new file in s3.

dev_jm's avatar
dev_jm
Best Answer
Level 1

This post its old but i solve with customPathDirectory, here the official doc. https: //spatie.be/docs/laravel-medialibrary/v10/advanced-usage/using-a-custom-directory-structure, in my case put this in my controller

$model->syncFromMediaLibraryRequest($request->file) ->addCustomHeaders([ 'path' => 'root', 'preview' => 'anotherRoot or root' ]) ->toMediaCollection('collection', 's3');

then in the customPathDirectory file i make this

public function getPath(Media $media): string { return $media->custom_properties['custom_headers']['path']; }

and finally add you customPathDirectory file in the config media-library

'path_generator' => \App\Services\MediaLibrary\CustomPathDirectory::class,

now u can send file to any directory as you want.

NOTE: the url have one space between https: and // just remove and go

1 like

Please or to participate in this conversation.