如何使用 window.open 设置文件名 [英] How to set a file name using window.open
问题描述
我正在尝试下载由 JavaScript 计算的临时结果.假设我有一个字符串 str
,我想下载一个包含 str
的文件并将其命名为 data.csv
,我正在使用以下内容代码:
I'am trying to download temporary result calculated by JavaScript. Say I have a string str
, I want to download a file contains str
and named it as data.csv
, I'm using the following code:
window.open('data:text/csv;charset=utf-8,' + str);
文件可以成功下载,但是如何自动命名文件data.csv
而不是每次手动设置名称?
The file can be successfully downloaded, but how can I name the file data.csv
automatically rather than set the name by hand each time?
推荐答案
您可以使用 元素的
download
属性来实现这一点.例如:
You can achieve this using the download
attribute for <a>
elements. For example:
<a href="1251354216241621.txt" download="your-foo.txt">Download Your Foo</a>
此属性指示应下载文件(而不是显示,如果适用)并指定应为下载的文件使用哪个文件名.
This attribute indicates that the file should be downloaded (instead of displayed, if applicable) and specifies which filename should be used for the downloaded file.
您可以使用 download
属性和 .click()
生成一个不可见的链接,而不是使用 window.open()
.
Instead of using window.open()
you could generate an invisible link with the download
attribute and .click()
it.
var str = "Name, Price
Apple, 2
Orange, 3";
var uri = 'data:text/csv;charset=utf-8,' + str;
var downloadLink = document.createElement("a");
downloadLink.href = uri;
downloadLink.download = "data.csv";
document.body.appendChild(downloadLink);
downloadLink.click();
document.body.removeChild(downloadLink);
不幸的是,并非所有浏览器都支持此功能,但添加它不会使其他浏览器的情况更糟:它们将继续下载带有无用文件名的文件.(这假设您使用的 MIME 类型是他们的浏览器尝试下载的.如果您试图让用户下载 .html
文件而不是显示它,这将获胜在不受支持的浏览器中对您没有任何好处.)
Unfortunately this isn't supported in all browsers, but adding it won't make things worse for other browsers: they'll continue to download the files with useless filenames. (This assumes that you're using a MIME type is that their browser attempts to download. If you're trying to let the user download an .html
file instead of displaying it, this won't do you any good in unsupported browsers.)
这篇关于如何使用 window.open 设置文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!