Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

swapnilnandgave's avatar

Get File Mime Type on Laravel 8 Filesystem

How would I get mime type of uploaded file?

0 likes
5 replies
sscotti's avatar

I think just: request->file('file')->getMimeType(), in your controller, where "file" key for the file uploaded. These are all useful:

$request->file('file')->getSize()
$contents = $request->file('file')->get();
$tmppath = $request->file('file')->path();
$request->file('file')->getClientOriginalName()
Log::info($tmppath);

https://laravel.com/api/8.x/Illuminate/Http/UploadedFile.html

https://laravel.com/api/8.x/Illuminate/Http/Testing/File.html#method_getMimeType

swapnilnandgave's avatar

I am looking for already uploaded file. Is there any helper method to get mime type from Storage::url or string url?

sscotti's avatar

Not sure if there is a native Laravel method. Detection of mime_types is done in various ways. Sometime from browser during upload, from the file extension or from headers in the actual file, so some are more reliable than others. I haven't tried this completely, but I've use them elsewhere:

 /**
  * Detects the MIME type of a given file
  * @param string $fileName The full path to the name whose MIME type you want to find out
  * @return string The MIME type, e.g. image/jpeg
  */
 static function getMimeType($fileName)
 {
     $mime = null;
     // Try fileinfo first
     if (function_exists('finfo_open')) {
         $finfo = finfo_open(FILEINFO_MIME);
         if ($finfo !== false) {
             $mime = finfo_file($finfo, $fileName);
             finfo_close($finfo);
         }
     }
     // Fallback to mime_content_type() if finfo didn't work
     if (is_null($mime) && function_exists('mime_content_type')) {
         $mime = mime_content_type($fileName);
     }
     // Final fallback, detection based on extension
     if (is_null($mime)) {
         $extension = self::getTypeIcon(getTypeIcon);
         if (array_key_exists($extension, self::$mimeMap)) {
             $mime = self::$mimeMap[$extension];
         } else {
             $mime = "application/octet-stream";
         }
     }
     return $mime;
 }

from here: https://hotexamples.com/examples/-/-/finfo_open/php-finfo_open-function-examples.html

abdou2000's avatar

Try this:

$request->file('file')->getClientMimeType();

getClientMimeType() method gets the mime type from the uploaded file you've given.

1 like

Please or to participate in this conversation.