使用 CakePHP 3.5 的 $this->response->withFile() 函数来 Return 一个 JPG 文件
Using CakePHP 3.5's $this->response->withFile() Function to Return a JPG File
我正在尝试使用 CakePHP 3.5 中的控制器读取文件并return它,但我运气不佳。
我在 /webroot 目录中有一个具有 777 权限的快速测试文件,我正在尝试使用以下代码 return 它:
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' 类型的零字节页面。
我在 Whosebug 或网络上找不到任何内容,一般来说,按照 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;
}
As shown in the above example, you must pass the file path to the method. [...]
响应对象是不可变的,你没有重新分配对象,因此你返回的是一个未修改的响应对象,正如评论中已经指出的,你应该传递一个路径,一个绝对路径,而不仅仅是文件名,否则将在 APP
常量指向的任何位置查找文件!
另见
我正在尝试使用 CakePHP 3.5 中的控制器读取文件并return它,但我运气不佳。
我在 /webroot 目录中有一个具有 777 权限的快速测试文件,我正在尝试使用以下代码 return 它:
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' 类型的零字节页面。
我在 Whosebug 或网络上找不到任何内容,一般来说,按照 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; }
As shown in the above example, you must pass the file path to the method. [...]
响应对象是不可变的,你没有重新分配对象,因此你返回的是一个未修改的响应对象,正如评论中已经指出的,你应该传递一个路径,一个绝对路径,而不仅仅是文件名,否则将在 APP
常量指向的任何位置查找文件!
另见