Get mime type of image from storage?
Asked Answered
S

1

10

I'm getting a file from storage using:

$image = Storage::get('test.jpg');

How can I get it's mime type?

I've tried:

$mime = Storage::mimeType($image);

With no luck.

I need the mime type so I can return the image as a response:

$response = Response::make($image, 200);
$response->header('Content-Type', $mime);
return $response;
Sharisharia answered 26/2, 2019 at 16:26 Comment(2)
You wont to download image?Ramsey
I do not want to download the image - I want to return an image as a response.Sharisharia
J
27

When using the Storage facade in a controller, you can return the image as a response in Laravel 5.7. The response() function will automatically set the headers required rather than attempting to do it yourself.

// Option #1
return Storage::response('test.jpg'); // Local storage
// Option #2
return Storage::disk('s3')->response('test.jpg'); // If you are using an S3 driver
// Option #3
return Storage::cloud()->response('test.jpg'); // Also S3 driver unless otherwise configured

This is not documented, but can be found by looking at the underlying Laravel code:

/vendor/laravel/framework/src/Illuminate/Filesystem/FilesystemAdapter.php

If you still need to get the mime type for any reason, you should be able to retrieve it by calling:

$mimeType = Storage::mimeType('test.jpg');
Johnathanjohnathon answered 14/5, 2019 at 18:29 Comment(2)
This does not seem to be available "out of the box". Maybe this has changed since 5.7? In 10.0, Storage::disc() returns \Illuminate\Contracts\Filesystem\Filesystem which does not have a response() method without customizing the filesystem (which is not as straightforward as one would prefer, at least looking at their docs alone): laravel.com/docs/10.x/filesystem#custom-filesystemsChantey
If you want to get the file mimetype for a file on a specific disk use: Storage::disk('s3_or_any_other_disk_name')->mimeType($filePath);Lobscouse

© 2022 - 2024 — McMap. All rights reserved.