create a download link in symfony2


download_route:
    pattern:  /download/{filename}
    defaults: { _controller: YourBundle:Controller:download }
And then in your controller,
public function downloadAction($filename)
{
    $request = $this->get('request');
    $path = $this->get('kernel')->getRootDir(). "/../web/downloads/";
    $content = file_get_contents($path.$filename);

    $response = new Response();

    //set headers
    $response->headers->set('Content-Type', 'mime/type');
    $response->headers->set('Content-Disposition', 'attachment;filename="'.$filename);

    $response->setContent($content);
    return $response;
}
For generating download link check Generating urls section of the doc.

for a nomal php , if the content is a file:

if (file_exists($file)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename='.basename($file));
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));
    ob_clean();
    flush();
    readfile($file);
    exit;
}
if is the content is a string:


php 
$content = 'This is supposed to be working... dammit';
$length = strlen($content);

header('Content-Description: File Transfer');
header('Content-Type: text/plain');//<<<<
header('Content-Disposition: attachment; filename=testfile.txt');
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . $length);
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Expires: 0');
header('Pragma: public');

echo $content;
exit;
?>


评论

热门帖子