如何在Symfony2中强制下载远程文件?

问题描述 投票:1回答:1

我的控制器看起来像这样:

public function downloadAction($filename) {
    // Adding url to filename
    $path = $this->container->getParameter('remotepath').$filename;

    // Checking if file exists
    $ch = curl_init($path);
    curl_setopt($ch, CURLOPT_NOBODY, true);
    curl_setopt($ch, CURLOPT_HEADER, true);
    curl_exec($ch);
    $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($code == 200) {
        // Get the file
        $file = file_get_contents($path);

        // Generate Response
        $response = new Response();

        $d = $response->headers->makeDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT, $filename);
        $response->headers->set('Content-Disposition', $d);

        $response->setContent($file);
    } else {
        $response = new Response();
        $response->setContent('File not found. ('.$filename.')');
        $response->headers->set('Content-Type', 'text/html');
        $response->setStatusCode(404);
    }
    return $response;
}

我想要完成的是获取远程文件(图像,pdf,...)并强制下载此文件。但由于某些原因,Symfony总是在浏览器中将标题和文件内容以纯文本( - >乱码)的形式输出。

我找不到原因!

编辑:我更改了代码,我只创建一个空的Response()并将其返回给控制器。在使用文件名调用downloadAction时,我将标题内容写入浏览器窗口。所以我用Firebug检查了标题,看起来Symfony用普通标题响应并打印我设置到内容的标题。对我做错了什么建议?

php symfony
1个回答
0
投票

这可以通过RedirectResponse在您的控制器方法中执行以下操作来完成。

return new RedirectResponse($yourRemoteDownloadUrl);

在此示例中,$yourRemoteDownloadUrl是一个PDF文件,它位于Amazon S3存储桶中。

适用于Symfony 2和3。

© www.soinside.com 2019 - 2024. All rights reserved.