How to create a link to download generated documents in symfony2?

后端 未结 5 1428
别跟我提以往
别跟我提以往 2020-12-15 10:53

Documents are created by the system and saved to the folder /web/downloads. I have created a view to display links which will allow a user to download the files, should the

5条回答
  •  爱一瞬间的悲伤
    2020-12-15 11:41

    This is the best solution i came up with so far, it allows you to serve downloads from outside of your "/var/www/web/" folder, which makes the file not accessible without running this script used to serve the file.

    This way you can check if the downloader has permission to download the file he wants.

    In this example i used "/var/www/downloads/" where i store all files i want to serve as a download:

    /**
     * http://api.symfony.com/2.2/Symfony/Component/HttpFoundation/BinaryFileResponse.html
     */
    use Symfony\Component\HttpFoundation\BinaryFileResponse;
    
    class OfflineToolController extends Controller
    {
        /**
         * @return BinaryFileResponse
         */
        public function downloadAction()
        {
            $path = $this->get('kernel')->getRootDir(). "/../downloads/"; 
            $file = $path.'my_file.zip'; // Path to the file on the server
            $response = new BinaryFileResponse($file);
    
            // Give the file a name:
            $response->setContentDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT,'my_file_name.zip');
    
            return $response;
        }
    
    }
    

    source: docs: http://symfony.com/doc/current/components/http_foundation/introduction.html

    (should work on versions above 2.2)

提交回复
热议问题