Ruby on Rails: How to download a file with send_file and still show a view
-
29-06-2021 - |
سؤال
I'm sending an email with a link to a downloadable brochure.
Here's my download action
def download
@thing = Thing.find_using_slug(params[:id])
send_file @thing.brochure.path,
:type => 'application/pdf',
:filename => "#{@thing.name}_brochure.pdf"
end
When the user clicks the link from the email it starts the download and then they are left with a blank screen. I'd like to render a landing page and still send the file.
المحلول
It might be a better idea for the link in the email to point to the action for the landing page, perhaps with something like a ?dl
querystring appended.
The landing page action could conditionally check for params.include?(:dl)
, and if found append Javascript like the following to the <head>
of the landing page HTML.
window.onload = function() {
setTimeout(function() {
window.location = 'URL TO DOWNLOAD ACTION HERE';
}, 2000);
}
It'd be good practice to also provide a link on the landing page (again, conditional on the presence of the ?dl
querystring) in case the user has Javascript disabled or doesn't want to wait the 2 seconds for the redirect.