强制下载 'data:text/plain' URL [英] Force download of 'data:text/plain' URL
问题描述
我想知道是否可以强制浏览器(至少是 Chrome)下载 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 会下载二进制 URL(例如 data:application/zip;base64,...
),但不会下载可以在浏览器内查看的文件(例如文本文件).
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.
有什么办法可以让 Chrome 下载一个 data:text/plain,...
URL?
Is there any way to make Chrome download a data:text/plain,...
URL?
推荐答案
截至目前,已经可以在 Chrome 中使用 .使用
dispatchEvent
,您可以随时将任何字符串下载为文件(即使使用自定义文件名).这是一个使用它的实用函数:
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);
};
用法:
downloadFile("foo.txt", "bar");
它使用 jQuery 和 webkit
前缀,但两者都可以避免.
It uses jQuery and the webkit
prefix, but both can be avoided.
这篇关于强制下载 'data:text/plain' URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!