Is there any way to specify a suggested filename w

2019-06-24 03:56发布

If for example you follow the link:

data:application/octet-stream;base64,SGVsbG8=

The browser will prompt you to download a file consisting of the data held as base64 in the hyperlink itself. Is there any way of suggesting a default name in the markup? If not, is there a JavaScript solution?

16条回答
对你真心纯属浪费
2楼-- · 2019-06-24 04:33

HTML only: use the download attribute:

<a download="logo.gif" href="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7">Download transparent png</a>


Javascript only: you can save any data URI with this code:

function saveAs(uri, filename) {
  var link = document.createElement('a');
  if (typeof link.download === 'string') {
    link.href = uri;
    link.download = filename;

    //Firefox requires the link to be in the body
    document.body.appendChild(link);
    
    //simulate click
    link.click();

    //remove the link when done
    document.body.removeChild(link);
  } else {
    window.open(uri);
  }
}

var file = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'
saveAs(file, 'logo.gif');

Chrome, Firefox, and Edge 13+ will use the specified filename.

IE11, Edge 12, and Safari 9 (which don't support the download attribute) will download the file with their default name or they will simply display it in a new tab, if it's of a supported file type: images, videos, audio files, …


If need better compatibility now, use the Flash-based Downloadify as a fallback.

查看更多
手持菜刀,她持情操
3楼-- · 2019-06-24 04:34

you can add a download attribute to the anchor element.

sample:

<a download="abcd.cer"
    href="data:application/stream;base64,MIIDhTC......">down</a>
查看更多
Fickle 薄情
4楼-- · 2019-06-24 04:37

There is a tiny workaround script on Google Code that worked for me:

http://code.google.com/p/download-data-uri/

It adds a form with the data in it, submits it and then removes the form again. Hacky, but it did the job for me. Requires jQuery.

This thread showed up in Google before the Google Code page and I thought it might be helpful to have the link in here, too.

查看更多
倾城 Initia
5楼-- · 2019-06-24 04:37

Here is a jQuery version based off of Holf's version and works with Chrome and Firefox whereas his version seems to only work with Chrome. It's a little strange to add something to the body to do this but if someone has a better option I'm all for it.

var exportFileName = "export-" + filename;
$('<a></a>', {
    "download": exportFileName,
    "href": "data:," + JSON.stringify(exportData, null,5),
    "id": "exportDataID"
}).appendTo("body")[0].click().remove();
查看更多
登录 后发表回答