I’d like to download an mp3 file instead of playing /streaming it in Chrome. What I would like is for files to download automatically when users click on the links (i.e. a standard left click) and not via the “Save As” dialogue, but to the users default download folder for their browser.
Here is my approach, but could not achieve it successfully. I tried to download but nothing happened. Please help.
<a href="javascript:" onclick="saveAs(testinglink.mp3)">Download mp3</a>
<script>
function saveAs(url) {
var filename = url.substring(url.lastIndexOf("/") + 1).split("?")[0];
var xhr = new XMLHttpRequest();
xhr.responseType = 'blob';
xhr.onload = function() {
var a = document.createElement('a');
a.href = window.URL.createObjectURL(xhr.response);
a.download = filename;
a.style.display = 'none';
document.body.appendChild(a);
a.click();
delete a;
};
xhr.open('GET', url);
xhr.send();
}</script>