St Klauz St Klauz - 4 years ago 103
Javascript Question

Download button to save something that's already online

I'm doing a download form. I want to make the submit button download something that's already online, and not only open that something that you can save while on it. I want the download to start when you click the button basically.

This is what I have right now:

<form method="get" action="http://i.stack.imgur.com/hw4jL.png">
<input type="submit" value="Download"/>
</form>

Answer Source

It's possible to force a download if you control the server by adding the header Content-Disposition: attachment. However, from the client (JavaScript or HTML) the only way to force a remote URL to be downloaded is using the <a download> attribute. You can't do it directly as a <form>'s native action.

You could wrap the button in a download link, and remove its type="submit" (and probably the <form> too in this case):

<a download href="http://i.stack.imgur.com/hw4jL.png"><input  value="Download" /></a>

Or you could have an invisible link triggered instead of submitting the form to a server:

<form onsubmit="downloadLink.click(); return false;">
  <input type="submit" value="Download"/>
  <a download href="http://i.stack.imgur.com/hw4jL.png" id="downloadLink"></a>
</form>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download