我遇到以下问题: 我想在route / getImage / {id}上返回一个Image 该函数如下所示:
public function getImage($id){
$image = Image::find($id);
return response()->download('/srv/www/example.com/api/public/images/'.$image->filename);
}
当我这样做时,它会将此返回给我:
FatalErrorException in HandleCors.php line 18:
Call to undefined method Symfony\Component\HttpFoundation\BinaryFileResponse::header()
我在控制器的开头有use Response;
。
我不认为HandleCors.php是问题,但无论如何:
<?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,但这并没有解决它。
答案 0 :(得分:36)
问题是你在->header()
没有该功能的对象(Response
类)上调用Symfony\Component\HttpFoundation\BinaryFileResponse
。 ->header()
函数是part of a trait,由Laravel的Response class使用,而不是基本的Symfony响应。
幸运的是,您可以访问headers
属性,因此您可以执行此操作:
$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 :(得分:0)
如果您创建了中间件来防止历史记录,现在当您想要下载文件时,您会收到以下错误:调用未定义的方法 Symfony\Component\HttpFoundation\BinaryFileResponse::header()
因此,您应该将 preventBackHistory 文件编辑为:
lastTimeToComplete
在您创建的 CORS.php 文件中,您应该放置以下代码行:
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;
}