htmlcssdownloadattributesmp3

How to make a download attribute for an mp3 file?


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!


Solution

  • 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>