34

I have got the following problem: I want to return an Image on the route /getImage/{id} The function looks like this:

public function getImage($id){
   $image = Image::find($id);
   return response()->download('/srv/www/example.com/api/public/images/'.$image->filename);
}

When I do this it returns me this:

FatalErrorException in HandleCors.php line 18:
Call to undefined method Symfony\Component\HttpFoundation\BinaryFileResponse::header()

I have got use Response; at the beginning of the controller. I dont think that the HandleCors.php is the problem but anyway:

<?php namespace App\Http\Middleware;
use Closure;

use Illuminate\Contracts\Routing\Middleware;
use Illuminate\Http\Response;

class CORS implements Middleware {

public function handle($request, Closure $next)
{
      return $next($request)->header('Access-Control-Allow-Origin' , '*')
            ->header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT, DELETE')
            ->header('Access-Control-Allow-Headers', 'Content-Type, Accept, Authorization, X-Requested-With, Application');
     }
}

I actually dont know why this happens since it is exactly like it is described in the Laravel Docs. I have updated Laravel when I got the error but this did not fix it.

12
  • Which version of Laravel are you using?
    – Philbert
    Mar 26, 2015 at 21:33
  • Version 5.0.21 after the update and before 5.0.14 Mar 26, 2015 at 21:35
  • You should be using return response()->download(public_path("images/'.$image->filename")); or something similar.
    – DutGRIFF
    Mar 26, 2015 at 22:05
  • well, the error seems pretty right: you cannot set an header of the $request, only of the Response..
    – Philbert
    Mar 26, 2015 at 22:16
  • And what is the solution because I am not sure what to do at the moment? Mar 26, 2015 at 22:17

6 Answers 6

75

The problem is that you're calling ->header() on a Response object that doesn't have that function (the Symfony\Component\HttpFoundation\BinaryFileResponse class). The ->header() function is part of a trait that is used by Laravel's Response class, not the base Symfony Response.

Fortunately, you have access to the headers property, so you can do this:

$response = $next($request);

$response->headers->set('Access-Control-Allow-Origin' , '*');
$response->headers->set('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT, DELETE');
$response->headers->set('Access-Control-Allow-Headers', 'Content-Type, Accept, Authorization, X-Requested-With, Application');

return $response;
8
  • I changed it like you said and it really did help but now get "Trying to get property of non-object" error in the second line. Mar 26, 2015 at 22:04
  • 2
    @Sebi55 eh my bad. Clearly ->set() isn't chainable.
    – treeface
    Mar 26, 2015 at 22:45
  • Yeah that was my idea too. Any other idea how to fix the middleware to work with the BinaryFileResponse? Mar 26, 2015 at 22:50
  • I don't understand your answer particularly but it worked for me. :)
    – Rohan
    Nov 18, 2015 at 7:32
  • @treeface, It worked for me thanks, but it didn't work before adding semicolon to each statements. can you please add semicolon for each of the statements?. It will be helpful for future users
    – manian
    Apr 25, 2017 at 9:30
13

You may want to exclude headers or set different headers for file download requests by checking the header method exists in the returned Closure.

File download requests typically have the header method omitted from Closure.


public function handle($request, Closure $next)
{
    $handle = $next($request);

    if(method_exists($handle, 'header'))
    {
        $handle->header('Access-Control-Allow-Origin' , '*')
               ->header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT, DELETE')
               ->header('Access-Control-Allow-Headers', 'Content-Type, Accept, Authorization, X-Requested-With, Application');
    }

    return $handle;
    
}

If you need to set headers for a file request (as other answer suggested) $handle->headers->set() can be used in an else condition:


public function handle($request, Closure $next)
{
    $handle = $next($request);

    if(method_exists($handle, 'header'))
    {
        // Standard HTTP request.

        $handle->header('Access-Control-Allow-Origin' , '*');

        return $handle;
    }

    // Download Request?

    $handle->headers->set('Some-Other-Header' , 'value')

    return $handle;
    
}
1

If you have created middleware to prevent back history and now when you want to download a file, you are getting the following error: Call to undefined method Symfony\Component\HttpFoundation\BinaryFileResponse::header()

You should therefore edit yout PreventBackHistory file to:

public function handle($request, Closure $next)
    {
 
        $headers = [
            'Cache-Control'      => 'nocache, no-store, max-age=0, must-revalidate',
            'Pragma'     => 'no-cache',
            'Expires' => 'Sun, 02 Jan 1990 00:00:00 GMT'
        ];
        $response = $next($request);
        foreach($headers as $key => $value) {
            $response->headers->set($key, $value);
        }
 
        return $response;       
    }

Inside your CORS.php file that you have created you should put the following lines of code:

 public function handle($request, Closure $next)
    {
        $response = $next($request);

        $response->headers->set('Access-Control-Allow-Origin' , '*');
        $response->headers->set('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT, DELETE');
        $response->headers->set('Access-Control-Allow-Headers', 'Content-Type, Accept, Authorization, X-Requested-With, Application');
        
        return $response;
     }
1
  • Changing the prevent back history file resolved the issue for us... Sep 2, 2022 at 10:55
0

This worked for me! I hope it will be helpful.

public function handle($request, Closure $next)
{
        
        $response = $next($request);
        $headers = [
            'Access-Control-Allow-Origin' => '*',
            'Access-Control-Allow-Methods' => 'GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS',
            'Access-Control-Allow-Headers' => '*',
        ];

        foreach($headers as $key => $value) {
            $response->headers->set($key, $value);
        }

        return $response;
}
0

use this method it's work for me

public function handle(Request $request, Closure $next) {

        $headers = [
'Cache-Control'      => 'nocache, no-store, max-age=0, must-revalidate',
'Pragma'     => 'no-cache',
'Expires' => 'Sun, 02 Jan 1990 00:00:00 GMT'
                 ];
        $response = $next($req**strong text**uest);## Heading ##
       foreach($headers as $key => $value) {
        $response->headers->set($key, $value);
          }

        return $response;


}
0

Modify your PreventBackHistory to allow your browser to download the excel sheet:

if ($response instanceof \Symfony\Component\HttpFoundation\BinaryFileResponse) {
        $response->headers->set('Cache-Control', 'no-cache, no-store, max-age=0, must-revalidate');
        $response->headers->set('Pragma', 'no-cache');
        $response->headers->set('Expires', 'Sat, 01 Jan 2000 00:00:00 GMT');
        return $response;
    }else{
        return $response->header('Cache-Control','nocache, no-store, max-age=0, must-revalidate')
            ->header('Pragma','no-cache')
            ->header('Expires','Sat, 26 Jul 1997 05:00:00 GMT'); 
    }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.