在Symfony2中下载上传的文件

Jas*_*ett 8 symfony

我的Symfony2应用程序允许用户上传文件.我想用户也可以下载他们的文件.

如果我直接使用PHP,我只输出相应的标题,然后输出文件的内容.我如何在Symfony2控制器中执行此操作?

(如果你在答案中使用了硬编码的文件名,这对我来说已经足够了.)

Jas*_*ett 15

我最终这样做了:

/** 
 * Serves an uploaded file.
 *
 * @Route("/{id}/file", name="event_file")
 * @Template()
 */
public function fileAction($id)
{   
    $em = $this->getDoctrine()->getEntityManager();

    $entity = $em->getRepository('VNNPressboxBundle:Event')->find($id);

    if (!$entity) {
        throw $this->createNotFoundException('Unable to find Event entity.');
    }   

    $headers = array(
        'Content-Type' => $entity->getDocument()->getMimeType(),
        'Content-Disposition' => 'attachment; filename="'.$entity->getDocument()->getName().'"'
    );  

    $filename = $entity->getDocument()->getUploadRootDir().'/'.$entity->getDocument()->getName();

    return new Response(file_get_contents($filename), 200, $headers);
}   
Run Code Online (Sandbox Code Playgroud)

  • 请注意:如果您使用的是Symfony master,则应使用[makeDisposition](http://symfony.com/doc/master/components/http_foundation.html#downloading-files) (4认同)