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



我正在尝试读取一个文件并使用 CakePHP 3.5 中的控制器返回它,但我运气不佳。

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

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 或一般的网络上找不到任何内容,按照 3.5 文档中的建议使用 withFile(( 函数给出了一个简单的示例。我错过了什么?

再次查看文档,您的代码略有不同:

public function sendFile($id)
{
    $file = $this->Attachments->getFile($id);
    $response = $this->response->withFile($file['path']);
    // Return the response to prevent controller from trying to render
    // a view.
    return $response;
}

如上面的示例所示,必须将文件路径传递给该方法。[...]

响应对象是不可变的,您

没有重新分配该对象,因此您返回了一个未修改的响应对象,并且正如注释中已经指出的,您应该传递一个路径,一个绝对路径,而不仅仅是文件名,否则文件将在APP常量指向的任何内容中查找!

参见

  • Cookbook> 控制器>请求和响应对象>发送文件>
  • 响应
  • Cookbook> Controller> Request & Response Object> Common Error with Immutable Response
  • API> \cake\http\response::withFile((

最新更新