Reputation: 828
In http://book.cakephp.org/2.0/en/controllers/request-response.html#cake-response-file we can find the instructions to force a download of a local file, but if we pass the path as a remote file (for example an image in Amazon S3) the request fail because it still looks for the file in the local filesystem.
Using media views (http://book.cakephp.org/2.0/en/views/media-view.html) works fine with remote paths, but it's a deprecated feature.
What is the best approach to force the download of a remote file using CakePHP?
thanks!
Upvotes: 1
Views: 3298
Reputation:
You can workaround this by doing the following.
In your html template, your anchor tag should be like
<a href="link_to_your_action" target="_blank" download="file_name">Download file</a>
Then you can use the location method of Cakephp's CakeResponse class.
$this->response->location($remoteURL);
return $this->response;
OR
simply
return $this->redirect($remoteUrl);
HTML Anchor tag:
In the anchor tag you are using _blank to not disturb your current page. Then href is the link to the controller action. And finally download attribute tells the browser to download the file instead of opening. Note: Check this link for browser support.
Controller action
Both the location and the redirect methods do the same thing to set the appropriate headers for response object. I personally prefer the first method since it looks like a more direct way of doing this.
Upvotes: 3
Reputation: 931
You could use a combination of HttpSocket to save it to a temporary directory and the new Cake-Response-File, I was looking for something similar to serve files from a CDN and came across your question.
http://book.cakephp.org/2.0/en/controllers/request-response.html#cake-response-file
$this->response->file(
$file['path'],
array('download' => true, 'name' => 'foo')
);
Though I appreciate this would require a download to the local server - someone else might have a better suggestion but this will work while you test.
Upvotes: 4