title: Download file when clicking on the link in Meteor
body: <p>I store the mp3 files on my server using <a href="https://github.com/CollectionFS/Meteor-CollectionFS" rel="nofollow">https://github.com/CollectionFS/Meteor-CollectionFS</a>. I want to allow user to download the file just by clicking on the link and the 'download' attribute should work fine here i.e.:</p>
  
  <pre><code> &lt;a href="/cfs/files/audio/ubcq5Xev4mkQ3sv5t/file.mp3" download="file.mp3"&gt;download&lt;/a&gt;
  </code></pre>
  
  <p>The problem is that the file is opening/playing in the browser instead of just start to downloading to disk.</p>
  
  <p>As discussed here <a href="https://code.google.com/p/chromium/issues/detail?id=373182" rel="nofollow">https://code.google.com/p/chromium/issues/detail?id=373182</a> I guest it is because of cross origin request, so I tried to follow the suggested solution and use this link</p>
  
  <pre><code>&lt;a href="#" download data-url="{{url}}" type="button" class="btn btn-default"&gt;download&lt;/a&gt;
  </code></pre>
  
  <p>with this handler</p>
  
  <pre><code>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();
      }
  }
  </code></pre>
  
  <p>Now the file is downloaded as expected, but for large files there is a strange delay between 'click' and start of download. Any better solution?</p>