CakePHP2の $this->response でファイルをダウンロードさせるときのIEファイル名文字化け解消
やりたいこと:PHPでファイルをダウンロードさせたい
CakePHP2でファイルをダウンロードさせる.公式から以下のようにすれば良いことがわかる.
download.php
public function sendFile($id) {
$file = $this->Attachment->getFile($id);
$this->response->file($file['path']);
// レスポンスオブジェクトを返すとコントローラがビューの描画を中止します
return $this->response;
}
参照:http://book.cakephp.org/2.0/ja/controllers/request-response.html
問題
IEでダウンロードするとファイル名に文字化けが起こる.
色々なサイトから,通常のPHPでは以下のようにすれば良いことがわかる.
download.php
header("Content-Type: application/octet-stream;");
header("Content-Disposition: attachment; filename="ファイル名"; filename*=UTF-8''URLエンコーディングされたファイル名);
echo file_get_contents("ファイル名");
CakePHP2ではどうすればよいのか?
download.php
public function sendFile($id) {
$file = $this->Attachment->getFile($id);
$content = 'attachment;';
$content .= 'filename='.$filename;
$content .= 'filename*=UTF-8\'\''.rawurlencode($filename);
$this->response->header('Content-Disposition', $content);
$this->response->file($file['path']);
// レスポンスオブジェクトを返すとコントローラがビューの描画を中止します
return $this->response;
}
無事IEでもファイル名が文字化けせずダウンロードできた.