Download file CakePHP 3

12,070

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.

source

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;
}
Share:
12,070
Alessio
Author by

Alessio

Updated on June 08, 2022

Comments

  • Alessio
    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
      MuntingInsekto over 8 years
      have you tried to remove WWW_ROOT . DS . in your file path?
  • Ng Sek Long
    Ng Sek Long over 5 years
    oic, so the return $this->response is important, got it!
  • Sergio
    Sergio almost 4 years
    Hi, Is Easy read doc CakePHP 3 Example "Sending Files" book.cakephp.org/3/en/controllers/…