Set content type with correct filename extension for downloadable files

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the web-development category.

Last Updated: 2024-11-21

For downloadable files (e.g. generated invoices) you need to set a Content Type header as well as a filename including the correct file extension, otherwise the browser will guess something bogus and the user has to save it explicitly as PDF when downloading.

Here was my original problematic code

send_data pdf.render,
  type: 'application/pdf',
  # This filename did not end in PDF, FYI
  filename: charge.stripe_invoice_number,
  disposition: 'inline'

And here is the fix:

send_data pdf.render,
  type: 'application/pdf',
  filename: "#{charge.stripe_invoice_number}.pdf",
  disposition: 'inline'