How to make a download attribute for an mp3 file?

Viewed 2740

I have been trying to make a download link for a mp3 file and I can't seem to have been doing anything. The mp3 file is in the right place but when I click on it, it just opens in a new tab playing the audio file. The file position is like this:

<a href="forsongstab/tracks/Villagers of Ioannina City - Age of Aquarius - 01 Welcome.mp3" download="Villagers of Ioannina City - Age of Aquarius - 01 Welcome"><img class="dli" src="../images/downloadicon.jpeg">01. Welcome</a>

If anyone can find a way to fix please let me know. Thank you!

3 Answers

A solution using javascript only:

function downloadBlob(blob, filename) {
  var a = document.createElement('a');
  a.download = filename;
  a.href = blob;
  document.body.appendChild(a);
  a.click();
  a.remove();
}

function downloadResource(url) {
  filename = url.split('\\').pop().split('/').pop();
  fetch(url, {
      mode: 'no-cors'
    })
    .then(response => response.blob())
    .then(blob => {
      let blobUrl = window.URL.createObjectURL(blob);
      downloadBlob(blobUrl, filename);
    })
    .catch(e => console.error(e));
}
<a href="#" onClick="javascript:downloadResource('https://file-examples.com/wp-content/uploads/2017/11/file_example_MP3_700KB.mp3')">01. Welcome</a>

You will need to add this HTTP header to your response to make the browser force a download:

Content-Disposition: attachment; filename=your_filename.mp3

For example, if you're using PHP on the server side, you can create a script that sends the above header followed by the actual file contents:

$path = $_GET['path'];
header('Content-Disposition: attachment; filename=' . basename($path));
readfile($path);

If you call this script download.php, then linking to download.php?path=/path/to/your/file.mp3 will make the browser pop-up a download dialog for file.mp3.

.then(response => response.blob()) lack return

Related