Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 581
Alessio Avatar asked Dec 05 '22 20:12

Alessio


2 Answers

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;
}
like image 136
Hasan Khan Avatar answered Dec 09 '22 15:12

Hasan Khan


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.

source

like image 44
user3082321 Avatar answered Dec 09 '22 14:12

user3082321