PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, January 12, 2022

[FIXED] cakephp file download link

 January 12, 2022     cakephp, php     No comments   

Issue

I've encountered a problem I'm trying to solve for more than two days now: I've built a Website using cakephp and everything is working just fine but I got stuck when I tried to implement download links to files stored under APP_DIR/someFolder/someFile.zip.

How do I set download links to files inside someFolder? I often stumbled over "Media Views" I tried implementing them but so far I've been unsuccessful.

Besides is there no easier way to make files downloadable?


Solution

Media Views is deprecated since version 2.3. You should use Sending files instead.

Check out this minimal example in your controller:

public function download($id) {
    $path = $this->YourModel->aMagicFunctionThatReturnsThePathToYourFile($id);
    $this->response->file($path, array(
        'download' => true,
        'name' => 'the name of the file as it should appear on the client\'s computer',
    ));
    return $this->response;
}

The first parameter of $this->response->file is relative to your APP directory. So calling $this->response->file('someFolder' . DS . 'someFile.zip') will download the file APP/someFolder/someFile.zip.

“Sending files” requires at least CakePHP version 2.0. Please also consider taking a look at the Cookbook link above.


If you are running an older version of CakePHP you should use Media Views as you already mentioned in your question. Use this code and refer to Media Views (Cookbook).

Here's the same method for older versions:

public function download($id) {
    $this->viewClass = 'Media';
    $path = $this->YourModel->aMagicFunctionThatReturnsThePathToYourFile($id);
    // in this example $path should hold the filename but a trailing slash
    $params = array(
        'id' => 'someFile.zip',
        'name' => 'the name of the file as it should appear on the client\'s computer',
        'download' => true,
        'extension' => 'zip',
        'path' => $path
    );
    $this->set($params);
}


Answered By - Jan
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing