【问题标题】:Download a file with Symfony2 [duplicate]使用 Symfony2 下载文件 [重复]
【发布时间】:2014-02-13 21:05:29
【问题描述】:

在我的项目中可以上传文件;我开发了这个阅读Symfony2 documentation

我没有在控制器中创建能够下载这些文件的操作的详细说明。

我该怎么办?

【问题讨论】:

    标签: php symfony download


    【解决方案1】:

    我的版本如下所示:

    /**
     * @Route("/download/{file_id}", name="download_file")
     */
    public function downloadAction($file_id)
    {
        // get your filepath from db somehow by file_id or whatever
        $path = ...
    
        $file = getimagesize($path);
    
        $response = new Response();
        $response->setContent(file_get_contents($path));
        $response->headers->set('Content-Type', $file['mime']);
        $response->headers->set('Content-Disposition', 'attachment; filename="' . $filename . '"');
    
        return $response;
    }
    

    【讨论】:

    • 在我的项目中,uploadDir 依赖于文件。要定义路径,我必须在对象内部调用 getUploadDir() 方法。但该方法受到保护。确定要公开吗?否则,我该怎么办?
    【解决方案2】:
    $response=new Response();
    $response->setContent(file_get_contents($localFilePath));
    

    对于强制下载,您可以使用:

    $file_url = 'http://www.myremoteserver.com/file.exe';
    header('Content-Type: application/octet-stream');
    header("Content-Transfer-Encoding: Binary"); 
    header("Content-disposition: attachment; filename=\"" . basename($file_url) . "\""); 
    readfile($file_url); // do the double-download-dance (dirty but worky)
    

    【讨论】:

    • 在我的项目中,uploadDir 依赖于文件。要定义路径,我必须在对象内部调用 getUploadDir() 方法。但该方法受到保护。确定要公开吗?否则,我该怎么办?
    猜你喜欢
    • 2013-05-31
    • 2015-12-04
    • 1970-01-01
    • 2020-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-23
    • 1970-01-01
    相关资源
    最近更新 更多