Symfony: stream download

To download file the Symfony way, add a download action and not to display layout unless there are errors.

In /path/to/your/app/modules/your_module/actions/actions.class.php:

public function executeDownload(sfWebRequest $request) {
    $file = Doctrine::getTable('File')->find($request->getParameter('id'));
    // check if file exists
    if (!$file->fileUploaded()) {
        $this->getUser()->setFlash('error', 'File does not exist.');
        return sfView::ERROR;
    // do any file information formatting
    // do any credential validation
    // dowload file
    $response = $this->getContext()->getResponse();
    $response->addCacheControlHttpHeader('Cache-control', 'must-revalidate, post-check=0, pre-check=0');
    $response->setContentType('application/octet-stream', true);
    $response->setHttpHeader('Content-transfer-encoding', 'binary');
    $response->setHttpHeader('Content-Disposition', 'attachement; filename=' . $file->getSlug() . '.' . $file->getExtension());
    return sfView::NONE;

Note that this assumes there’s a file table in database storing information about this file.

Leave a Reply

Your email address will not be published. Required fields are marked *