【问题标题】:Using CakePHP 3.5's $this->response->withFile() Function to Return a JPG File使用 CakePHP 3.5 的 $this->response->withFile() 函数返回一个 JPG 文件
【发布时间】:2018-09-21 15:07:34
【问题描述】:

我正在尝试读取文件并使用 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 或网络上找不到任何东西,给出了一个简单的示例,使用 3.5 文档中推荐的 withFile() 函数。我错过了什么?

【问题讨论】:

  • 从我阅读的文档看来,您可能必须为其提供完整路径,而不仅仅是文件名。

标签: php cakephp httpresponse cakephp-3.x cakephp-3.5


【解决方案1】:

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

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

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

响应对象是不可变的,您没有重新分配对象,因此您返回的是未修改的响应对象,并且如 cmets 中所述,您应该传递一个路径,一个绝对路径,而不是只是一个文件名,否则将在 APP 常量指向的任何地方查找该文件!

另见

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-26
    • 2014-06-23
    • 2018-08-05
    • 1970-01-01
    • 2017-10-20
    • 1970-01-01
    相关资源
    最近更新 更多