[英]How to trigger a file download when clicking an HTML Link <a> to other website
[英]Download file when clicking on the link in Meteor
我使用https://github.com/CollectionFS/Meteor-CollectionFS将mp3文件存储在我的服务器上。 我想让用户只需点击链接就可以下载文件,'download'属性在这里工作正常,即:
<a href="/cfs/files/audio/ubcq5Xev4mkQ3sv5t/file.mp3" download="file.mp3">download</a>
问题是文件在浏览器中打开/播放而不是开始下载到磁盘。
正如这里讨论的那样https://code.google.com/p/chromium/issues/detail?id=373182我是客人,因为交叉来源请求,所以我尝试按照建议的解决方案并使用此链接
<a href="#" download data-url="{{url}}" type="button" class="btn btn-default">download</a>
用这个处理程序
Template.podcastItemSummary.events({
'click a.btn-download': function(event, instance){
event.preventDefault();
downloadFile($(event.currentTarget).attr('data-url'));
}
});
if (Meteor.isClient) {
downloadFile = function(sUrl){
window.URL = window.URL || window.webkitURL;
var xhr = new XMLHttpRequest();
xhr.open('GET', sUrl, true);
xhr.responseType = 'blob';
xhr.onload = function(e) {
var res = xhr.response;
var blob = new Blob([res], {type:"audio/mp3"});
url = window.URL.createObjectURL(blob);
var a = document.createElement("a");
a.style.display = "none";
a.href = url;
a.download = sUrl.split('/').pop();
document.body.appendChild(a);
a.click();
window.URL.revokeObjectURL(url);
};
xhr.send();
}
}
现在文件按预期下载,但对于大文件,“点击”和开始下载之间存在奇怪的延迟。 更好的解决方案?
正如@ZuzEL所写,解决方案是用?download
结束链接
<a href="/cfs/files/audio/ubcq5Xev4mkQ3sv5t/file.mp3?download" target="_parent">download</a>
我将url存储在一个单独的集合中,现在我意识到我应该只存储文件的id(ubcq5Xev4mkQ3sv5t),因为有一个设计解决方案https://github.com/CollectionFS/Meteor-CollectionFS/wiki/How-to : -提供-A-下载按钮
Template.fileList.helpers({
files: function () {
return Files.find();
}
});
和模板
<template name="fileList">
<div class="fileList">
{{#each files}}
<div class="file">
<strong>{{this.name}}</strong> <a href="{{this.url download=true}}" class="btn btn-primary" target="_parent">Download</a>
</div>
{{/each}}
</div>
</template>
它产生一个包含令牌的URL
<a href="/cfs/files/audio/WdBfMy2gSLRwx3XKw/file.mp3?token=eyJhdXRoVG9rZW4iOiJ2bHd6WGNoT3ktUzNoOTJUUHJnLXFMZDd6OE9yS3NHMFNkaGMwbTRKWVVUIn0%3D&download=true" target="_parent">Download</a>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.