I have been trying to get the extension from an uploaded file, searching on google, I got no results.
The file already exists in a path:
\Storage::get('/uploads/categories/featured_image.jpg);
Now, How can I get the extension of this file above?
Using input fields I can get the extension like this:
Input::file('thumb')->getClientOriginalExtension();
Thanks.
This question is related to
php
laravel
filesystems
You can use the pathinfo() function built into PHP for that:
$info = pathinfo(storage_path().'/uploads/categories/featured_image.jpg');
$ext = $info['extension'];
Or more concisely, you can pass an option get get it directly;
$ext = pathinfo(storage_path().'/uploads/categories/featured_image.jpg', PATHINFO_EXTENSION);
Yet another way to do it:
//Where $file is an instance of Illuminate\Http\UploadFile
$extension = $file->getClientOriginalExtension();
If you just want the extension, you can use pathinfo
:
$ext = pathinfo($file_path, PATHINFO_EXTENSION);
//working code from laravel 5.2
public function store(Request $request)
{
$file = $request->file('file');
if($file)
{
$extension = $file->clientExtension();
}
echo $extension;
}
Do something like this:
if($request->hasFile('video')){
$video=$request->file('video');
$filename=str_random(20).".".$video->extension();
$path = Storage::putFileAs(
'/', $video, $filename
);
$data['video']=$filename;
}
The Laravel way
Try this:
$foo = \File::extension($filename);
Or can use the Extension Splitter Trickster::getExtention()
function of https://github.com/secrethash/trickster
Trickster::getExtention('some-funny.image.jpg');
It returns jpg
Tested in laravel 5.5
$extension = $request->file('file')->extension();
return $picName = time().'.'.$request->file->extension();
The time()
function will make the image unique then the .$request->file->extension()
gets the image extension for you.
You can use this it works well with Laravel 6 and above.
Source: Stackoverflow.com