How do I create a download link that doesn't blink?

1.1k views Asked by At

I would like the user to be able to download a file from a method I set up in a controller. Further, I don’t want the URL to change in my browser when the user downloads the file. I have this link set up

<%= link_to image_tag("cc_icon.png"), scenario_download_cc_path(subscription.scenario), target: '_blank' %>

The problem is, there is a screen blink as a new tab is spawned to generate the download. This looks visually unappealing. I have seen other sites where you click the link and something starts downloading without a blink. How do I do that?

Edit: Here is the function invoked by the link

def download_cc
  scenario = Scenario.find(params[:scenario_id])
  send_data scenario.cc_data, filename: "#{scenario.title}.imscc", type: 'application/zip', :disposition => 'attachment'
end
4

There are 4 answers

1
Greg Navis On BEST ANSWER

I did some local testing and my hypothesis is that Turbolinks is messing things up. I recommend that you remove target: '_blank' from the link and add data: { turbolinks: false } to opt-out of Turbolinks for this particular link. The code after changes should look like this:

<%= link_to image_tag("cc_icon.png"), scenario_download_cc_path(subscription.scenario), data: { turbolinks: false } %>

Your controller action looks good and needs no changes.

6
MishMash95 On

Remove target

At the moment, you are setting target="_blank", this is telling the browser that when you click the URL, you want to open a new tab. Removing this should just begin the download without opening a tab or window.

< Optional extra info below as I misread your question: >

Formatting the appearance of links

Are you using any HTML or CSS for the design of the site? If so, you can apply css state properties such as "active" "hover" "visited" "link" in your css classes.

Lets say you had a link:

<a href="example.com">My Link</a>

If you created a css file and customised the properties for the link:

a:visited {
    text-decoration: none;
}

that will allow you to alter the appearance of a visited link. You can then use any css property to customise the appearance in any way you want.

Adding CSS files to Ruby app

With Ruby, you can use: <%= stylesheet_link_tag "filename" %> to load in a css file.

Sources: http://www.w3schools.com/css/css_link.asp How do I use CSS with a ruby on rails application?

4
BigRon On

As long as you use send_file you should not see a screen blink.

The scenario_download_cc_path(subscription.scenario) action in your controller should look like this:

file_path = File.join(Rails.root, "/public/myfile.whatever")
send_file file_path

The behavior on Chrome and IE appears the same whether your link does or does not include target: '_blank'

1
maxpogorelov On

Just add a "download" attribute to your link:

<%= link_to image_tag("cc_icon.png"), scenario_download_cc_path(subscription.scenario), download: true %>