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

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

$response = new BinaryFileResponse(file_create_url("public://cal/211443-event.ics"));
  • This is what you want. – Kevin Mar 29 at 23:46
  • Yes, return it from a controller or set it directly in $form_state: $form_state->setResponse($response); – 4k4 Mar 30 at 9:30
  • Nice. I didn’t know that. I’ll edit my post to include it. – Jaypan Mar 30 at 9:31
  • Thank you for the response. I ll try it and I ll post the results here – Dimitris Markopoulos Mar 31 at 12:01
  • 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 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 set in the Save file dialog that the browser will show to the user.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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