簡體   English   中英

單擊Meteor中的鏈接時下載文件

[英]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&amp;download=true" target="_parent">Download</a>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM