3

I have a form with the submit button. And I have a file in '/sites/default/files/tmp/my_doc.docx' I'm trying to download the file upon submitting the form.

Here is my code

public function submitForm(array &$form, FormStateInterface $form_state){
   $filename = '/sites/default/files/tmp/my_doc.docx';
   $response = new BinaryFileResponse($filename);
   $form_state->setResponse($response);
}

But it doesnt't work properly.

That is, the file is being downloaded but has the same name that name of php file containing this code.

Could you clarify me, what have I done wrong ?

1 Answer 1

6

You need to set the filename with setContentDisposition, as the constructor only takes the file, but doesn't set the name itself:

$response->setContentDisposition(
    ResponseHeaderBag::DISPOSITION_ATTACHMENT,
    'my_doc.docx'
);

Don't forget to add use Symfony\Component\HttpFoundation\ResponseHeaderBag; at the top of your file.

There is quite a bit more you can do with BinaryFileResponse as well, so check out some of the methods.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.