我允许用户从本地文件系统中选择一个mp3文件,然后允许下载相同的文件。是为了学习的目的。
<script type="text/javascript">
window.onload = function() {
document.querySelector('#musicFile').addEventListener('change', function(e){
var file = e.target.files[0];
console.log(e, file);
if(file.type.match('audio.*')) { // if its an audio file
var fReader = new FileReader();
fReader.onload = function(ev) { //onload event
var dataUrl = ev.target.result;
var downloadCon = document.querySelector('#download')
downloadCon.href = dataUrl;
};
fReader.readAsDataURL(file); //start reading the file
}
});
}
</script>HTML主体:
<body>
<div class="controls">
<input type="file" id="musicFile">
<a id='download'href='#' download='music.mp3' class='downloadLink'>
Download File
</a>
</div>
</body>当我单击Download File时,什么都不会发生。你能告诉我我做错了什么吗?
发布于 2015-09-17 10:37:44
您不需要使用FileReader来做到这一点。简单地说,您需要创建一个URLObject并使A标记指向它。这方面的代码(在Chrome和下测试):
<script type="text/javascript">
window.onload = function() {
document.querySelector('#musicFile').addEventListener('change', function(e){
var file = e.target.files[0];
console.log(e, file);
if(file.type.match('audio.*')) { // if its an audio file
document.getElementById( 'download' ).href = URL.createObjectURL(file);
}
});
}
</script>为了更具体地说明我在您的代码中所做的工作,我删除了所有的FileReader代码,并添加了
document.getElementById( 'download' ).href = URL.createObjectURL(file);就在这地方。我没碰你的HTML。
希望这能有所帮助。
https://stackoverflow.com/questions/32601848
复制相似问题