Symfony BinaryFileResponse set filename

2019-04-20 04:35发布

问题:

is it possible to set own filename when file is returned by Symfony2 controller throught BinaryFileResponse response?

回答1:

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'
);