Download file CakePHP 3
Solution 1
I don't think file()
has id
option also WWW_ROOT
doen't need DS
after it.
public function download($id=null) {
$filePath = WWW_ROOT .'files'. DS . $id;
$this->response->file($filePath ,
array('download'=> true, 'name'=> 'file name'));
}
Path are repeated because your file path was wrong and file()
is prepending APP
to the path you are providing.
If the path is not an absolute path that resolves to a file, APP will be prepended to the path.
Solution 2
public function file_download()
{
$file_path = WWW_ROOT.'uploads'.DS.'file_name.doc';
$this->response->file($file_path, array(
'download' => true,
'name' => 'file_name.ppt',
));
return $this->response;
}
Alessio
Updated on June 08, 2022Comments
-
Alessio almost 2 years
I try to download uploaded files which are saved in the folder 'files' in the webroot. Here is my download function in the controller:
public function download($id=null) { $this->response->file(WWW_ROOT . DS .'files'. $id ,array('download'=> true,'id'=> 'file name.pdf', 'name'=> 'file name'));
And in the view I have the following:
<td> <?= $this->Html->link('Download', ['controller' => 'Articles', 'action' => 'download',$id]) ?></td>
First of all this results in an error under the download button (undefined variable id) and then I get the (more global) error: The requested file C:\xampp\htdocs\articles\src\C:\xampp\htdocs\articles\webroot\files was not found or not readable. I cant really understand why the part C:\xampp\htdocs\articles is repeated twice and how to fix those problems and download uploaded files (not only the specified file in the function $this->response->file but any file found by its id). Any help would be greatly appreciated!
-
MuntingInsekto over 8 yearshave you tried to remove
WWW_ROOT . DS .
in your file path?
-
-
Ng Sek Long over 5 yearsoic, so the
return $this->response
is important, got it! -
Sergio almost 4 yearsHi, Is Easy read doc CakePHP 3 Example "Sending Files" book.cakephp.org/3/en/controllers/…