Get an image extension from an uploaded file in Laravel

非 Y 不嫁゛ 提交于 2019-11-27 14:23:17

问题


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.


回答1:


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);



回答2:


The Laravel way

Try this:

$foo = \File::extension($filename);



回答3:


Yet another way to do it:

//Where $file is an instance of Illuminate\Http\UploadFile
$extension = $file->getClientOriginalExtension();



回答4:


Tested in laravel 5.5

$extension = $request->file('file')->extension();



回答5:


If you just want the extension, you can use pathinfo:

$ext = pathinfo($file_path, PATHINFO_EXTENSION);



回答6:


 //working code from laravel 5.2

 public function store(Request $request)
 {
          $file = $request->file('file');
            if($file)
            {
                    $extension =  $file->clientExtension();
            }
            echo $extension;
 }



回答7:


Or can use the Extension Splitter Trickster::getExtention() function of https://github.com/secrethash/trickster

Trickster::getExtention('some-funny.image.jpg'); It returns jpg



来源:https://stackoverflow.com/questions/38403558/get-an-image-extension-from-an-uploaded-file-in-laravel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!