yougotnet's avatar

putFile S3 Result

When I use Storage::disk('s3')->putFile() it returns a string that is not the file name and it stores the file in S3 but not the name of the file; it stores it with some character string and the extension of the file.

Original file name: ADataLayout.pdf S3 file name: eLEgWorqnjaUClFtxQO0aBGj5gezSIVoy2LLvdS2.pdf

Is this by design or do I have a setting making this do this?

0 likes
3 replies
LaryAI's avatar
Level 58

The behavior you're experiencing is by design. The putFile method automatically generates a unique ID to prevent file name collisions when storing the file in the S3 bucket. This is why you see a random string instead of the original file name.

If you want to preserve the original file name when storing the file in S3, you should use the putFileAs method instead. This method allows you to specify the directory, the file, and the name you want to use when storing the file.

Here's an example of how you can use putFileAs to store the file with its original name:

use Illuminate\Support\Facades\Storage;

// Assuming you have a file in the $request object
$file = $request->file('file');
$originalName = $file->getClientOriginalName();
$filePath = 'your/desired/path'; // The directory path within your S3 bucket

// Store the file in S3 with the original file name
$path = Storage::disk('s3')->putFileAs($filePath, $file, $originalName);

// $path will contain the path to the file including the original file name

Make sure to replace 'your/desired/path' with the actual directory path where you want to store the file in your S3 bucket, and $request->file('file') with the actual file instance you are dealing with.

This way, you'll have control over the file name that is stored in S3. Keep in mind that when using putFileAs, you are responsible for handling any potential file name collisions that may occur.

amitsolanki24_'s avatar

@yougotnet When you use putFile() it will generate unique random name.

If you want to store your custom name than use putFileAs() function or use put() function

$file = $request->file('file');
$originalName = $file->getClientOriginalName();
$path = 'test/'.$originalName;

Storage::disk('s3')->put($path, file_get_contents($file));

yougotnet's avatar

@amitsolanki24_ I like that feature but I started using the S3 API so I can leverage Versioning and Delete Markers. I assume the Storage Facade can't handle these features.

I realize I have to generate my own string.

Please or to participate in this conversation.