Clyde Clyde - 4 months ago 18
Javascript Question

Download button

I am making an audio player, and I would like to include a button that downloads the current track. I have tried the common solutions people suggest, but these only open the .mp3 in a new tab and play it. This is what I am using:

document.getElementById("dlButton").addEventListener("click", function(){
window.location = "tracks/CFKZ.mp3";});


I saw another solution here on stack overflow:

<form method="get" action="file.doc">
<button type="submit">Download!</button>
</form>


I don't understand this. It doesn't make sense to me why a download button would need to send information to the file that is to be downloaded.

Answer

HTML5 solution with a simple anchor tag using the 'download' attribute (doesn't require any javascript):

<a href="/music/somefile.mp3" download="somefile.mp3">Download mp3</a>

the download attribute can also be used to rename the file:

<a href ="/music/3ri3nlfkndfoiweuio.mp3" download="TheManWhoSoldTheWorld.mp3" >Download a Bowie Hit</a>

will download as 'TheManWhoSoldTheWorld.mp3'

edit for cross browser support (relies on Modernizr - which you should use if worried about cross-browser support https://modernizr.com/):

maybe this fiddle will help: https://jsfiddle.net/abigwonderful/3jfqz5j0/2/ or just open this window in multiple browsers and click 'Run code snippet' below:

var a = document.createElement('a');
if (typeof a.download == "undefined") {
    //append some text to inform the user 
    //they should right-click the link to download
    //example:
    var downloadDiv = document.getElementById('download');
    downloadDiv.innerHTML = "Right-click the link and select 'Save as...' to download the mp3";

} 
<a href="/music/somefile.mp3" download="somefile.mp3">Download mp3</a>
<div id="download"></div>

Comments