Alessio Alessio - 10 months ago 115
PHP Question

Download file CakePHP 3

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!

Answer Source

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.