I have a custom module where I need to create a file and download it on form submission. So far, I managed to created the file and save it in public folder, but I cannot find a way to download it to client. This is the code I wrote so far.

public function submitForm(array &$form, FormStateInterface $form_state) {
  $file_name = $date.'-event.ics';
  $cal_file = file_unmanaged_save_data('file content',"public://cal/$file_name",FILE_EXISTS_RENAME);
  return new RedirectResponse(file_create_url("public://cal/211443-event.ics"));

2 Answers 2


You can return a BinaryFileResponse from a controller, or as 4k4 has added:

$response = new BinaryFileResponse("public://cal/211443-event.ics");
  • 1
    This is what you want.
    – Kevin
    Mar 29, 2019 at 23:46
  • 1
    Yes, return it from a controller or set it directly in $form_state: $form_state->setResponse($response);
    – 4uk4
    Mar 30, 2019 at 9:30
  • 1
    Nice. I didn’t know that. I’ll edit my post to include it.
    – Jaypan
    Mar 30, 2019 at 9:31
  • 1
    Thank you for the response. I ll try it and I ll post the results here Mar 31, 2019 at 12:01
  • 1
    You might be able to remove the call to file_create_url(). Let me know if that's the case and I'll update.
    – Jaypan
    Mar 31, 2019 at 12:47

That is what, for example, the Drupal\locale\Form\ExportForm class does. See the code used in ExportForm::submitForm().

$response = new BinaryFileResponse($uri);
$response->setContentDisposition('attachment', $filename);

$response->setContentDisposition() sets the Content-Disposition header with the given filename. That is the filename used for the Save file dialog the browser will show to users.


Your Answer

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

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