如何从Symfony中的视图下载文件

I have a app made with Symfony2 and in my twig template, I show a table with some pdf files.

This pdf files (one for user) are stored in /app/var/pdf/xxx.pdf.

If I use:

<a href="{{ 'entity.pdf' }}">PDF</a>

My path is correct, for example: symfony/app/var/pdf/123123.pdf, but when I click in the link, my browser return a 404 Not Found error. Obviusly I have checked that the file is stored in this path.

Any help?

Thanks in advance.

You better need to store this file in public web dir, and then create link to it like:

<a href="{{ asset('web/var/pdf/xxx.pdf') }}"/>PDF</a>

But browsers open pdf files in new tab. And if you really want to force dowload of this file, need to use headers. Use this question for help Symfony2 - Force file download

To force download the pdf file try this in the controller.

/**
 * @Route("/download/{id}",name="pdf_download")
 */
public function downloadAction($id) {


    $downloadedFile = $repository->findOneBy(
            array(
                'id' => $id,
            )
    );
    $response=new Response();


    $response = new Response();
    $response->headers->set('Content-type', 'application/octet-stream');
    $response->headers->set('Content-Disposition', sprintf('attachment; filename="%s"',          $downloadedFile->getFilename() ));
    $response->setContent(file_get_contents($downloadedFile->getAbsolutePath()));
    $response->setStatusCode(200);
    $response->headers->set('Content-Transfer-Encoding', 'binary');
    $response->headers->set('Pragma', 'no-cache');
    $response->headers->set('Expires', '0');
    return $response;

 }

And in the template

  <a href={{path('pdf_download',{'id':file.id})}}>{{file.filename}}</a>

You can use absolute URL like below

<a href="{{ absolute_url(asset('uploads/YOURPATCH/'))}}pdf_download" download>
 Download 
</a>