I'm using Laravel's file storage functionality to save a file:
public function dataPost(Request $request) { $fileInForm = 'doc'; if ($request->hasFile($fileInForm)) { $file = $request->file($fileInForm); if ($file->isValid()) { // Filename is hashed filename + part of timestamp $hashedName = hash_file('md5', $file->path()); $timestamp = microtime() * 1000000; $newFilename = $hashedName . $timestamp . '.' . $file->getClientOriginalExtension(); Storage::disk('local')->put($newFilename, $file); } } }
This does save the file, but inside a directory named the same as the file, for example:
storage/app/952d6c009.jpg/952d6c009.jpg
or
storage/app/234234234.jpg/234234234.jpg
Is this expected? Is there any way to just store the file without a separate directory for each file?
Thanks!
To upload files to storage in Laravel, use MAMP or XAMPP as a local web server, define a database name in MySQL, and add the correct configuration in the . env file.
The __DIR__ can be used to obtain the current code working directory. It has been introduced in PHP beginning from version 5.3. It is similar to using dirname(__FILE__). Usually, it is used to include other files that is present in an included file.
$request->image->hashName(); You will get the same name that Laravel generates when it creates the file name during the store method. $path = $request->image->getClientOriginalName(); Have a look at the the UploadedFile API Docs class for other methods available to you.
Retrieve the file pathphp $storagePath = Storage::disk('local')->getDriver()->getAdapter()->getPathPrefix();
you need to provide the file contents in the second argument not file object, try this:
Storage::disk('local')->put($newFilename, file_get_contents($file));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With