Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
898 views
in Technique[技术] by (71.8m points)

file - Force download of 'data:text/plain' URL

I was wondering whether it is possible to force a browser (at least Chrome) to download a data:text/plain URL.

Chrome does download binary URLs (e.g. data:application/zip;base64,...), but it does not download files that can be viewed inside the browser (such as text files).

What I already tried with no luck so far is this:

data:text/plain;content-disposition=attachment;filename=test.txt;...

But it seems like I cannot add headers like this.

Is there any way to make Chrome download a data:text/plain,... URL?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

As of now, it has been made possible to use <a download> in Chrome. Using dispatchEvent, you can download any string as file (even with a custom filename) whenever you want. Here's a utility function to use it:

var downloadFile = function(filename, content) {
  var blob = new Blob([content]);
  var evt = document.createEvent("HTMLEvents");
  evt.initEvent("click");
  $("<a>", {
    download: filename,
    href: webkitURL.createObjectURL(blob)
  }).get(0).dispatchEvent(evt);
};

Usage:

downloadFile("foo.txt", "bar");

It uses jQuery and the webkit prefix, but both can be avoided.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...