Laravel中的BinaryFileResponse未定义 [英] BinaryFileResponse in Laravel undefined
问题描述
我遇到了以下问题:
我想在路线上返回一个图像/ getImage / {id}
该函数如下所示:
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()
我有使用Response;
在开头控制器。
我不认为HandleCors.php是问题但无论如何:
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');
}
}
我实际上不知道为什么会这样,因为它确实是就像它在Laravel Docs中描述的那样。
当我收到错误时我更新了Laravel但这并没有解决它。
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.
推荐答案
问题在于你在没有该功能的 Response
对象上调用 - > header()
( Symfony \Component\HttpFoundation\BinaryFileResponse
class)。 - > header()
函数是 Laravel使用的特征的一部分响应类,而不是基本的Symfony响应。
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.
幸运的是,您可以访问 headers
property,所以你可以这样做:
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;
这篇关于Laravel中的BinaryFileResponse未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!