首页 文章

使用CakePHP 3.5的$ this-> response-> withFile()函数返回JPG文件

提问于
浏览
0

我正在尝试读取一个文件并使用CakePHP 3.5中的控制器返回它并且我没有太多运气 .

我有一个快速测试文件,位于/ webroot目录中,具有777权限,我尝试使用以下代码返回它:

public function thumbnail( $order_id = null, $image_id = null ) {

    $this->response->withFile( $order_id.'-'.$image_id.'.jpg' );
    return $this->response;
}

当我点击那个控制器时(即/ orders / thumbnail / KC9BW0 / 1)我在浏览器中返回的是一个带有'text / html'类型的零字节页面 .

我在StackOverflow或Web上找不到任何东西,通常使用3.5文档中建议的withFile()函数给出一个简单的例子 . 我错过了什么?

1 回答

  • 0

    再看看文档,你的代码略有不同:

    public function sendFile($ id)
    {
    $ file = $ this-> Attachments-> getFile($ id);
    $ response = $ this-> response-> withFile($ file ['path']);
    //返回响应以防止控制器尝试渲染
    // 一个看法 .
    返回$ response;
    }
    如上例所示,您必须将文件路径传递给方法 . [...]

    响应对象是不可变的,你没有重新分配对象,因此你返回一个未修改的响应对象,并且如评论中所述,你应该传递一个路径,一个 absolute path ,而不仅仅是一个文件名,否则文件将被查找无论 APP 恒定指向什么!

    也可以看看

    • Cookbook > Controllers > Request & Response Objects > Response > Sending Files

    • Cookbook > Controllers > Request & Response Objects > Common Mistakes with Immutable Responses

    • API > \Cake\Http\Response::withFile()

相关问题