【问题标题】:How can i set multiple Header Keys with Slim Framework 3如何使用 Slim Framework 3 设置多个标题键
【发布时间】:2020-02-26 14:05:06
【问题描述】:

我正在使用下面的示例代码向浏览器返回数据

$response->write($image);
return $response->withHeader('Content-Type', 'image/jpeg');

效果很好,但是如果我还想返回 Content-Length ,我该怎么做? 到目前为止,我发现的唯一选择是将响应复制到如下所示的新对象中,但如果我在响应中有 $image,我认为这不是有效的。

$response = $response->withAddedHeader('Content-Length', strlen($image));

我尝试将它作为数组但不起作用..

【问题讨论】:

    标签: php slim slim-3


    【解决方案1】:

    引用Slim 3 docs

    提醒
    与 withHeader() 方法不同,此方法将新值附加到已存在的相同标头名称的值集中。 Response 对象是不可变的。此方法返回具有附加标头值的 Response 对象的副本。

    withHeader()appendedHeader() 方法都返回响应对象的副本。因此,即使您没有将 $response->withHeader() 的返回值分配给变量并直接返回结果,您仍然在使用响应对象的副本。

    关于您对效率的关注,您应该使用streams instead of string 作为响应正文。以下是如何使用流返回图像作为响应的示例:

    <?php
    
    use Slim\App;
    use Slim\Http\Request;
    use Slim\Http\Response;
    use Slim\Http\Body;
    
    return function (App $app) {
        $container = $app->getContainer();
        $app->get('/', function(Request $request, Response $response) {
            $image = fopen('sample.jpg', 'r');
            return $response->withBody(new Body($image))
                ->withHeader('Content-Type', 'image/jpeg')
                ->withAddedHeader('Content-Length', fstat($image)['size']);
        });
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-20
      • 2013-06-12
      • 2010-11-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多