0

I have this mp3 file stored in my firebase database and when a user clicks on a download button I want to download the file:

I've tried doing

<a href='https://firebasestorage.googleapis.com/v0/b/soundcloud-9491a.appspot.com/o/Microsoft%20Windows%20XP%20Startup%20Sound.mp3?alt=media&token=31351745-698d-469a-a6b5-86c3076f35f3'>Download</a>

But when I do this, it only opens up the mp3 video in the google browser, and does not download it. **EDIT Is there a way doing it with an audio element? Because the default audio element provides a download button, would it be possible to create a function that would click on that download button?

User123123
  • 485
  • 1
  • 5
  • 13

1 Answers1

0

function forceDownload(blob, filename) {
  var a = document.createElement('a');
  a.download = filename;
  a.href = blob;
  // For Firefox https://stackoverflow.com/a/32226068
  document.body.appendChild(a);
  a.click();
  a.remove();
}

// Current blob size limit is around 500MB for browsers
function downloadResource(url, filename) {
  if (!filename) filename = url.split('\\').pop().split('/').pop();
  fetch(url, {
      headers: new Headers({
        'Origin': location.origin
      }),
      mode: 'cors'
    })
    .then(response => response.blob())
    .then(blob => {
      let blobUrl = window.URL.createObjectURL(blob);
      forceDownload(blobUrl, filename);
    })
    .catch(e => console.error(e));
}
<a href="javascript:downloadResource('https://file-examples-com.github.io/uploads/2017/11/file_example_MP3_700KB.mp3', 'best.wav')">Try a successful download</a><br>
<a href="javascript:downloadResource('https://firebasestorage.googleapis.com/v0/b/soundcloud-9491a.appspot.com/o/Microsoft%20Windows%20XP%20Startup%20Sound.mp3?alt=media&token=31351745-698d-469a-a6b5-86c3076f35f3', 'best.wav')">This download will not work since the <code>Access-Control-Allow-Origin</code> header is set.</a>

The normal download attribute will not work. You need to use a custom function to download cross-origin files. In your case, this cannot be done as the server you are using sends a Access-Control-Allow-Origin header which means that the domain must be the same.

See Chrome 65 blocks cross-origin <a download>. Client-side workaround to force download? for more information.

trinalbadger587
  • 1,905
  • 1
  • 18
  • 36