Javascript:表单输入音频到音频下载链接?

时间:2018-03-11 07:32:12

标签: javascript html forms filereader

这是一个奇怪的问题,但一段时间以来让我很困惑。

我有这个音频输入:

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

当您提交某些音频时,我想在此元素上添加下载链接:

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

我尝试过这样的奇怪事情:

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);
}

但是,上述操作会导致Chrome中出现下载错误。

以下是用于测试目的的HTML文件:

<!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>
编辑:我刚注意到你可以嵌入HTML文件:

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>

任何帮助都会很棒!

1 个答案:

答案 0 :(得分:1)

诀窍是你应该把它变成 ObjectURL ,然后顾名思义你可以将它用作href的网址, 所以现在已经在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();

此处它正在PlayCode.io

工作