Return Binary Image Data from Laravel with Correct Content Type

Viewed 1724

I have a Laravel controller that retrieves binary image data from some source like the database or an API and returns it as the response:

class ExampleController extends Controller 
{

  // ...

  public function testImage(Request $request)
  {
    // This is a binary string not a stream or file handle
    $binaryImageData = $this->repository->getImage($request->query);

    return response($binaryImageData);
  }
}

However since Laravel returns a Content-Type header value of `text/html' when I open this in the browser the binary data is rendered as HTML.

I can't guarantee that I will have access to the correct content type for the image data.

So how would I go about detecting and returning the correct type?

2 Answers

I think those methods can help :

mb_detect_encoding

(Detect character encoding.)

$encoding = mb_detect_encoding($binaryImageData, mb_list_encodings(), true);

Symfony\Component\HttpFoundation\File\UploadedFile::getClientMimeType

(Returns the file mime type.)

$mimetype = $binaryImageData->getClientMimeType();

Example of response headers using content type ($mimetype) :

      return response(Storage::get($file->path))
        ->withHeaders([
          'Content-disposition' => 'attachment; filename=' . $file->file_name,
          'Access-Control-Expose-Headers' => 'Content-Disposition',
          'Content-Type' => $file->mimetype,
        ]);

After further research I have determined there is no Laravel specific way to detect the mime type of a binary string. However there is a generic PHP way:

function detectMimeType(string $input)
{
    return (new finfo(FILEINFO_MIME_TYPE))->buffer($input);
}

Also Laravel currently has league/filesystem as a dependency, which in turn has league/mime-type-detection which provides it's own class based wrapper for the finfo. I would recommend to anyone who prefers league/mime-type-detection to require it explicitly in their projects composer.json file in case Laravel drops the requirement in the future.

Related