Alex Doe
Alex Doe

Reputation: 359

How to force download for remote file in Symfony2?

My Controller looks like this:

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;
}

What I am trying to accomplish is to get a remote file (image, pdf, ...) and force a download for this file. But for some reason Symfony is always putting out the header and the file contents as plain text (-> gibberish) in the browser.

I can't find the reason why!

Edit: I altered the code so, that I only create an empty Response() and return it for the controller. On calling the downloadAction with a filename I get the header contents written into the browser window. So I checked the headers with Firebug and it seems like Symfony responds with normal headers and prints the headers I set to the content. Any suggestions on what I am doing wrong?

Upvotes: 1

Views: 2684

Answers (1)

crmpicco
crmpicco

Reputation: 17181

This can be done with RedirectResponse by doing the following in your controller method.

return new RedirectResponse($yourRemoteDownloadUrl);

In this example $yourRemoteDownloadUrl is a PDF file which is living in a Amazon S3 bucket.

Works in Symfony 2 and 3.

Upvotes: -3

Related Questions