3 ways to give users, a download

Here are 3 of the most common ways to enable downloads on your webpage

Let’s Begin

Anchor Link

The most easiest way is to provided a direct link

<a href="link_to_download.html?file=filename.ext">Download</a>

But this may cause redirection. To over come this, you may add target="_blank". This will cause the download to occur in a new tab

<a href="link_to_download.html?file=filename.ext" target="_blank">Download</a>

Pros

  • Easy to implement

Cons

  • May cause redirection or open a new tab
  • Only works for GET requests

Form submit

This method makes use of a form to generate a request

form = $('<form>').attr({ method: 'POST', action: 'link_to_download.html'});

param = $('<input>').attr({ name: 'file', value : 'filename.ext'});

form.append(param).appendTo('body').submit().remove()

Pros

  • Works with POST and GET requests

Cons

  • May cause redirection
  • Requires javascript to be enabled

iFrame

This method makes use of an iframe to generate a request

$('<iframe>')
    .attr({ src: "link_to_download.html?file=filename.ext", style: "visibility:hidden;display:none"})
    .appendTo($('body'));

Pros

  • Does not cause redirection

Cons

  • Works with only GET requests
  • Requires javascript to be enabled


Summary

Anchor Form iFrame
requires JavaScript No Yes Yes
causes redirection Yes Yes No
Works with POST No Yes No

Leave a Reply