an odd fellow

仕事のメモ

Symfony2でmp3などの音楽ファイルや画像ファイルなどの静的コンテンツをユーザに直接ダウンロードさせる

/getMusic

とかにアクセスした瞬間ダウロードさせるあれ。公式のドキュメントを参照すると静的コンテンツを直接ダウンロードさせるには BinaryFileResponse を使うのが良いということです。

use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;

$response = new BinaryFileResponse('path/hoge.mp3');
$response->headers->set('Content-type', 'audio/mpeg');
BinaryFileResponse::trustXSendfileTypeHeader();
$response->setContentDisposition(
    ResponseHeaderBag:;DISPOSITION_ATTACHMENT,
    'hoge.mp3'
);
return $response;

Stack OverFlow には readfile や fread で読み込んでレスポンスしている人ばかりだったけど、おそらく BinaryFileResponse を使ってやったほうがきちんとした http ヘッダが作られて良さそう。

効率的なWebアプリケーションの作り方 ~PHPによるモダン開発入門

効率的なWebアプリケーションの作り方 ~PHPによるモダン開発入門