23

Is it possible to set a custom filename when the file is returned by a Symfony2 controller using a BinaryFileResponse response?

1
  • 1
    use $response->headers->set('Content-Disposition', sprintf('attachment; filename="%s"', $filename)); Commented Mar 7, 2015 at 20:55

1 Answer 1

53

Yes. The BinaryFileResponse class has a method setContentDisposition() that takes the file name as the second argument.

The first argument is the way the file should be delivered. It can be ResponseHeaderBag::DISPOSITION_ATTACHMENT (or just the string "attachment") if the file should be offered for downloading, or ResponseHeaderBag::DISPOSITION_INLINE (or "inline") if you want the file to be shown in the browser (you may want to do this with images, for example).

A full code example:

<?php
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;

$response = new BinaryFileResponse('/path/to/myfile');
$response->setContentDisposition(
    ResponseHeaderBag::DISPOSITION_ATTACHMENT,
    'file_name.txt'
);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.