强制下载“data:text / plain”URL [英] Force download of 'data:text/plain' URL

查看:970
本文介绍了强制下载“data:text / plain”URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否可以强制浏览器(至少Chrome)下载数据: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?

推荐答案

截至目前,已经有可能使用< a download> 在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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆