Link for cakephp file download

I ran into a problem that I’ve been trying to solve for more than two days: I created a website using cakephp and everything works fine, but I got stuck when I tried to implement download links to saved files under APP_DIR/someFolder/someFile.zip.

How to set download links to files inside someFolder? I often came across "Media Views", I tried to implement them, but so far I have not been successful.

Also, is there no easier way to make files downloadable?

+5
source share
2 answers

Multimedia views have been deprecated since version 2.3. Instead, use File Upload .

Check out this minimal example in the 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\ computer',
    ));
    return $this->response;
}

$this->response->file APP. $this->response->file('someFolder' . DS . 'someFile.zip') APP/someFolder/someFile.zip.

" " CakePHP 2.0. .


CakePHP, Media Views, . Media Views (Cookbook).

:

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\ computer',
        'download' => true,
        'extension' => 'zip',
        'path' => $path
    );
    $this->set($params);
}
+16

CakePHP 3

AppController Write, .

public function downloadResponse() {
    return $this->response
        ->withHeader('Content-Type', 'application/pdf')
        ->withHeader('Content-Disposition', 'attachment;')
        ->withHeader('Cache-Control', 'max-age=0')
        ->withHeader('Cache-Control', 'max-age=1')
        ->withHeader('Expires', 'Mon, 26 Jul 1997 05:00:00 GMT')
        ->withHeader('Last-Modified', gmdate('D, d M Y H:i:s') . ' PDT')
        ->withHeader('Cache-Control', 'cache, must-revalidate')
        ->withHeader('Pragma', 'public')
        ->withFile($filePath, ['download' => true]);
} 
0

All Articles