BinaryFileResponse in Laravel undefined

2019-02-12 07:01发布

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.

1条回答
该账号已被封号
2楼-- · 2019-02-12 07:48

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;
查看更多
登录 后发表回答