<a> tag with download attribute and dataUrl href?

时间:2017-08-24 12:46:09

标签: javascript html5 download

I am experiencing strange behavior in various browsers when trying to use download attribute in <a> tag when href is dataUrl.

Code snippet:

var a = document.createElement('a');
a.href = [generated dataUrl];
a.download = filename;
console.log(a.outerHTML);
a.click();

Sample contents of tag generated (from console.log line above):

<a href="data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64,UEsDBAoA...Qwwe=" download="testfile.xlsx" ></a>
<a href="data:image/png;base64,iVBORw...ElFTkSuQmCC" download="testfile.png"></a>

Console output/behavior:

  • Chrome: Files download as expected, and both png and xls are usable.
  • FireFox: Nothing happens. No console warnings/errors shown.
  • EDGE:

    • Console message: Navigation occurred. data:image/png;base64,iVBORw...

    • Console warning: DOCTYPE expected. Consider adding a valid HTML5 doctype: "".

  • IE11: Console: nothing; tries to "open data:image/png;base64,iVBORw..." url in current window.

generated dataUrlare double-checked and are fine, which is also shown by Chrome behavior.

I thought that <a href="data:[mime][;base64],[encoded data] ></a>" download="filename.ext" was pretty much a standard thing by now.

Question:

Is there a better (i.e. cross-browser compatible) way to invoke download of JavaScript generated files?

1 个答案:

答案 0 :(得分:1)

某些浏览器不支持html5下载属性 在这种情况下,您可以使用filesaver.js

if(typeof link.download !== 'undefined'){
  //use <a> download
}
else{
  blob = toBlob(imageURIData);
  saveAs(blob, name);//use filesaver.js
}