How to create a link that download a file in Symfony

帅比萌擦擦* 提交于 2021-02-07 08:43:24

问题


I did some research and I found this post: How to create a link to download generated documents in symfony2?

I tried the solution, but it show my pdf in the browser, but what I want is that when someone click the link, it directly download the file. Is ther a way to do that with Symfony?

Kévin Duguay


回答1:


Set up an action. This uses annotation for the route. YOu can of course use yml or xml or whatever you are currently using

/**
 * @Route("/download", name="download_file")
**/
public function downloadFileAction(){
    $response = new BinaryFileResponse('path/to/pdf.pdf');
    $response->setContentDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT,'pdf.pdf');
    return $response;
}

Twig template:

<a href="{{path('download_file')}}">Download file</a>


来源:https://stackoverflow.com/questions/28910112/how-to-create-a-link-that-download-a-file-in-symfony

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!