1

This is a weird question, but it's been confusing me for a while.

I have this audio input:

<input required type="file" id="inputAudio" accept="audio/*" onchange="downloadLink(this);">

When you submit some audio, I'd like to add a download link on this element:

<a id="blah">Download Audio</a>

I've tried doing weird things such as this:

function downloadLink(element) {
    var file = element.files[0];
    var reader = new FileReader();
    reader.onload = function(e) {
        var data = file.type + ";charset=utf-8," + encodeURIComponent(e.target.result);
        var link = document.getElementById("blah");
        link.href = "data:" + data;
        link.download = "someName." + file.name.split(".").pop();
    };
    reader.readAsDataURL(file);
}

However, the above causes a download error in Chrome.

Here's a HTML file for testing purposes:

<!DOCTYPE html>
<html>
    <head>
        <title>Weird Problem</title>
        <script>
        function downloadLink(element) {
            var file = element.files[0];
            var reader = new FileReader();
            reader.onload = function(e) {
                var data = file.type + ";charset=utf-8," + encodeURIComponent(e.target.result);
                var link = document.getElementById("blah");
                link.href = "data:" + data;
                link.download = "someName." + file.name.split(".").pop();
            };
            reader.readAsDataURL(file);
        }
        </script>
    </head>
    <body>
        <input required type="file" id="inputAudio" accept="audio/*" onchange="downloadLink(this);">
        <a id="blah">Download Audio</a>
    </body>
</html>

EDIT: I just noticed you can embed HTML files:

function downloadLink(element) {
 var file = element.files[0];
 var reader = new FileReader();
 reader.onload = function(e) {
  var data = file.type + ";charset=utf-8," + encodeURIComponent(e.target.result);
  var link = document.getElementById("blah");
  link.href = "data:" + data;
  link.download = "someName." + file.name.split(".").pop();
 };
 reader.readAsDataURL(file);
}
<!DOCTYPE html>
<html>
 <head>
  <title>Weird Problem</title>
 </head>
 <body>
  <input required type="file" id="inputAudio" accept="audio/*" onchange="downloadLink(this);">
  <a id="blah">Download Audio</a>
 </body>
</html>

Any help would be fantastic!

MysteryPancake
  • 1,365
  • 1
  • 18
  • 47

1 Answers1

1

the trick is you should just turn it into an ObjectURL then as the name suggest you can use it as url for href, so now been tested on safari, Chrome, FireFox :

var file = element.files[0];
var link = document.getElementById("blah");
link.href = window.URL.createObjectURL(file);
link.download = "someName." + file.name.split(".").pop();

here it's working at PlayCode.io

nullqube
  • 2,959
  • 19
  • 18