Return Binary Image Data from Laravel with Correct Content Type

  http, laravel, mime, php, response

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)
  {
    $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?

Source: Laravel

Leave a Reply