0

I'm trying to read a file and return it with a controller in CakePHP 3.5 and I'm not having much luck.

I have a quick test file sitting in the /webroot directory with 777 permissions and am trying to return it with this code:

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

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

When I hit that controller (ie. /orders/thumbnail/KC9BW0/1) All I get back in the browser is a zero byte page with 'text/html' type.

I can't find anything on StackOverflow or the web in general giving a simple example of this using the withFile() function in as recommended in the 3.5 documentation. What am I missing?

ndm
  • 59,784
  • 9
  • 71
  • 110
Dan Berlyoung
  • 1,639
  • 2
  • 17
  • 36

1 Answers1

0

Have a look at the docs again, your code is slightly different:

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. [...]

Response objects are immutable, you did not reassign the object, thus you are returning an unmodified response object, and as already stated in the comments, you should pass a path, an absolute path, not just a filename, otherwise the file will be looked up in whatever the APP constant points to!

See also

ndm
  • 59,784
  • 9
  • 71
  • 110