单击Meteor中的链接时下载文件

时间:2015-10-08 22:11:08

标签: javascript meteor download

我使用https://github.com/CollectionFS/Meteor-CollectionFS将mp3文件存储在我的服务器上。我想让用户只需点击链接下载该文件即可下载'属性应该在这里正常工作,即:。

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

现在按预期方式下载文件,但是对于大文件,“点击”之间会出现奇怪的延迟。并开始下载。有更好的解决方案吗?

1 个答案:

答案 0 :(得分:2)

正如@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:-Provide-a-download-button

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>

生成一个包含令牌的网址

<a href="/cfs/files/audio/WdBfMy2gSLRwx3XKw/file.mp3?token=eyJhdXRoVG9rZW4iOiJ2bHd6WGNoT3ktUzNoOTJUUHJnLXFMZDd6OE9yS3NHMFNkaGMwbTRKWVVUIn0%3D&amp;download=true" target="_parent">Download</a>
相关问题