使用JavaScript将文件存储到本地计算机(下载)

时间:2022-05-19 15:07:39

I want to store a file to a local machine.

我想将文件存储到本地计算机。

For HTML5, we can use cookies and local storage to store data to a local machine. Local storage uses key-value pairs (json) to store data. However, I want to save data in a different format, in XML for example.

对于HTML5,我们可以使用cookie和本地存储将数据存储到本地计算机。本地存储使用键值对(json)来存储数据。但是,我想以XML格式保存不同格式的数据。

On websites such as convertonlinefree.com, when a file has been converted, the file will automatically begin downloading.

在convertonlinefree.com等网站上,当文件被转换后,该文件将自动开始下载。

So, I am considering a way to do this: When the user clicks a button, the XML file would automatically be downloaded. Is this possible? If so, how could I do that?

因此,我正在考虑一种方法:当用户单击按钮时,将自动下载XML文件。这可能吗?如果是这样,我怎么能这样做?

2 个解决方案

#1


2  

You can create invisible element, such as a and emulate click on it, to download a file, check my codepen for demo.

您可以创建不可见元素,例如a和模拟点击它,下载文件,检查我的codepen以进行演示。

The important part is this:

重要的是这个:

var text = xmlContent.value;
// Create element.
a = document.createElement('a');
// Attach href attribute with value of your file.
a.setAttribute("href", "data:application/xml;charset=utf-8," + text);
// HTML5 property, to force browser to download it.
a.setAttribute("download", "my.xml");
a.click();

Optionally you can replace application/xml part with intentionally incorrect MIME type, to force browser to download file instead of trying to display it.

(可选)您可以使用故意不正确的MIME类型替换application / xml部件,以强制浏览器下载文件而不是尝试显示它。

#2


0  

What you'll want to use is Data_URI_scheme which basically means you have to base64 encode your file to download it.

你想要使用的是Data_URI_scheme,这基本上意味着你必须对你的文件进行base64编码才能下载它。

So something like this should work:

所以像这样的东西应该工作:

window.location = 'data:application/xml;base64,'+ btoa("<xml>data in the file</xml>")

#1


2  

You can create invisible element, such as a and emulate click on it, to download a file, check my codepen for demo.

您可以创建不可见元素,例如a和模拟点击它,下载文件,检查我的codepen以进行演示。

The important part is this:

重要的是这个:

var text = xmlContent.value;
// Create element.
a = document.createElement('a');
// Attach href attribute with value of your file.
a.setAttribute("href", "data:application/xml;charset=utf-8," + text);
// HTML5 property, to force browser to download it.
a.setAttribute("download", "my.xml");
a.click();

Optionally you can replace application/xml part with intentionally incorrect MIME type, to force browser to download file instead of trying to display it.

(可选)您可以使用故意不正确的MIME类型替换application / xml部件,以强制浏览器下载文件而不是尝试显示它。

#2


0  

What you'll want to use is Data_URI_scheme which basically means you have to base64 encode your file to download it.

你想要使用的是Data_URI_scheme,这基本上意味着你必须对你的文件进行base64编码才能下载它。

So something like this should work:

所以像这样的东西应该工作:

window.location = 'data:application/xml;base64,'+ btoa("<xml>data in the file</xml>")