2013年10月15日火曜日

[cakephp] ファイルをダウンロードする

file_get_contentsを使う場合
1
2
3
4
5
6
Configure::write('debug', 0); // デバッグをOFFに
$this->autoRender = false; // オートレンダーをOFFに
$this->header('Content-Type: application/octet-stream');
$this->header('Content-Length: '.filesize($filepath));
$this->header('Content-disposition: attachment; filename="'.$filename.'"');
echo file_get_contents($filepath);
cakephp 1.3 MediaView を使う場合
1
2
3
4
5
6
7
8
9
10
Configure::write('debug', 0); // デバッグをOFFに
$this->view = 'Media';
$params = array(
    'id' => 'example.zip',
    'name' => 'example',
    'extension' => 'zip',
    'download' => true,
    'path' => APP . 'outside_webroot_dir' . DS , // APP/webroot からの相対パスもしくはフルパス
);
$this->set($params);
cakephp 2.X MediaView を使う場合 viewがviewClassとなる しかし2.3で撤廃となっているので2.4以降は次のCakeResponse::downloadを使う
1
2
3
4
5
6
7
8
9
10
Configure::write('debug', 0); // デバッグをOFFに
$this->viewClass = 'Media';
$params = array(
    'id' => 'example.zip',
    'name' => 'example',
    'extension' => 'zip',
    'download' => true,
    'path' => 'files' . DS , // APP/webroot からの相対パスもしくはフルパス
);
$this->set($params);
cakephp 2.4 以降であれば
1
2
3
4
Configure::write('debug', 0); // デバッグをOFFに
$this->autoRender = false; // オートレンダーをOFFに
$this->response->file('files/example.zip'); // APP/webroot からの相対パスもしくはフルパス
$this->response->download('example.zip');

0 件のコメント:

コメントを投稿