从Laravel中的上传文件中获取图像扩展名

Ita*_*ges 32 php filesystems laravel

我一直试图从上传的文件中获取扩展名,在谷歌搜索,我没有得到任何结果.

该文件已存在于路径中:

\Storage::get('/uploads/categories/featured_image.jpg);
Run Code Online (Sandbox Code Playgroud)

现在,我如何获得上述文件的扩展名?

使用输入字段我可以像这样获得扩展:

Input::file('thumb')->getClientOriginalExtension();
Run Code Online (Sandbox Code Playgroud)

谢谢.

Alf*_* EM 43

Laravel的方式

试试这个:

$foo = \File::extension($filename);
Run Code Online (Sandbox Code Playgroud)

  • 复制并粘贴 \File::extension('/uploads/categories/featured_image.jpg') ; 并将返回 jpg (2认同)

Dan*_*rgo 36

还有另一种方法:

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

  • 危险:这将获得CLIENT扩展名,而不是真正的mime类型的扩展名,而应使用`extension()` (3认同)

Ami*_*ein 36

在laravel 5.5中测试

$extension = $request->file('file')->extension();
Run Code Online (Sandbox Code Playgroud)

  • 感谢您抽出时间提供答案。正是因为像您这样乐于助人的同伴,我们才能够作为一个社区一起学习。这里有一些关于如何让你的答案更好的提示:[我如何写出一个好的答案](https://stackoverflow.com/help/how-to-answer)。 (2认同)

Jer*_*ris 19

您可以使用PHP内置的pathinfo()函数:

$info = pathinfo(storage_path().'/uploads/categories/featured_image.jpg');
$ext = $info['extension'];
Run Code Online (Sandbox Code Playgroud)

或者更简洁,你可以通过一个选项直接得到它;

$ext = pathinfo(storage_path().'/uploads/categories/featured_image.jpg', PATHINFO_EXTENSION);
Run Code Online (Sandbox Code Playgroud)


ayn*_*ber 7

如果您只想要扩展程序,可以使用pathinfo:

$ext = pathinfo($file_path, PATHINFO_EXTENSION);
Run Code Online (Sandbox Code Playgroud)


BCP*_*YAK 5

 //working code from laravel 5.2

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


小智 5

return $picName = time().'.'.$request->file->extension();
Run Code Online (Sandbox Code Playgroud)

time()功能将使图像独一无二,然后.$request->file->extension()为您获取图像扩展名。

您可以使用它,它与 Laravel 6 及更高版本配合良好。