I want to host on my webpage an external url containing a mp3 file. The problem is that clicking on that link will open the player, i have to right click and "Save link as" in order to download the file. Is there any solution to force the file download?
I don't want to download the file and then use headers to force the download.
In most browsers, clicking on the link will open the file directly in the browser. But, if you add the download attribute to the link, it will tell the browser to download the file instead. The download attribute works in all modern browsers, including MS Edge, but not Internet Explorer.
Method 1: How to Trigger a File Download by Clicking an HTML Button? You need to utilize the <input> tag to create an HTML button and set its value to “Download”. The value is a user-defined attribute and can be set as per the user's wish.
On your computers desktop, right click on the item. Choose the 'Send to' option and then choose 'Compressed (zip) folder'. This will place your download in a zip folder.
Now the HTML5 spec defines a very useful download
attribute on hyperlinks that basically allows to force download behavior on client-side, regardless of what comes in Content-Type
and Content-Disposition
from the server:
In some cases, resources are intended for later use rather than immediate viewing. To indicate that a resource is intended to be downloaded for use later, rather than immediately used, the
download
attribute can be specified on thea
orarea
element that creates thehyperlink
to that resource.
<...>
The
download
attribute, if present, indicates that the author intends the hyperlink to be used for downloading a resource. The attribute may have a value; the value, if any, specifies the default filename that the author recommends for use in labeling the resource in a local file system.
So all you need to do is add the attribute to your hyperlink and the browsers that support it would understand that the content needs to be downloaded:
<a href="http://example.com/media.mp3" download>Download Your File</a>
You can even suggest a different name for the downloaded file by setting the attribute value:
<a href="http://example.com/media.mp3" download="check this out.mp3">Download Your File</a>
More info and demos:
Browser support: caniuse.com
Downloading generated content
You can even make a link that will download a content that you generated, as long as there is a way to get a base64-encoded data URI for it:
<a href="data:application/octet-stream;base64,YOUR_ENCODED_DATA" download="song.mp3">Download</a>
For more details on saving generated content, refer to this article by Eli Grey:
Saving generated files on the client-side
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With