BinaryFileResponse in Laravel undefined

2022-08-30 14:08:45

我遇到了以下问题:我想在路由/getImage/{id}上返回图像,该函数如下所示:

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()

我已经在控制器的开头。我不认为HandleCors.php是问题所在,但无论如何:use Response;

<?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,但这并没有解决它。


答案 1

问题是你调用的对象没有该函数(类)。该函数是Laravel的响应类使用的特性的一部分,而不是基本的Symfony Response。->header()ResponseSymfony\Component\HttpFoundation\BinaryFileResponse->header()

幸运的是,您可以访问该属性,因此您可以执行以下操作: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;

答案 2

您可能希望通过检查返回的方法是否存在来排除标头或为下载请求设置不同的标头。fileheaderClosure

文件下载请求通常省略了 中的方法。headerClosure


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;
    
}

如果您需要为请求设置标头(如其他答案所建议的那样),可以在以下条件下使用:file$handle->headers->set()else


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;
    
}

推荐