如何以编程方式在 Javascript 中创建可由用户下载的客户端文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15350895/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to programmatically create a client side file in Javascript that can be downloaded by the user?
提问by ZenBalance
I wanted to experiment creating a Javascript application that takes input from the user in a form and then generates a file based on the user's form input.
我想尝试创建一个 Javascript 应用程序,该应用程序从用户的表单中获取输入,然后根据用户的表单输入生成一个文件。
The file should then be downloadable by the user all without touching the server.
该文件应该可以由用户下载,而无需接触服务器。
How do you create a file on the client side with JavaScript and where on the client side could it be stored so that it can be downloaded without being first created on the server?
您如何使用 JavaScript 在客户端创建文件以及它可以存储在客户端的哪个位置,以便可以在不首先在服务器上创建的情况下下载它?
Update: To be more specific as Graham answered, I was looking for way to create the file without necessarily touching the file system itself, but just creating a file object (a Blob) that could be downloaded by the user. Thanks Graham!
更新:更具体地说,正如 Graham 回答的那样,我正在寻找创建文件的方法,而不必接触文件系统本身,而只是创建一个可由用户下载的文件对象(Blob)。谢谢格雷厄姆!
回答by Graham Robertson
One way to do this without having to use the filesystem is to create blobs. Let's say we have a bunch of data (in your case, from a form) and we wish to save it to a text "file". We could actually do something as follows:
无需使用文件系统即可执行此操作的一种方法是创建 blob。假设我们有一堆数据(在您的情况下,来自表单)并且我们希望将其保存到文本“文件”中。我们实际上可以做如下事情:
var formBlob = new Blob([someStringVariable], { type: 'text/plain' });
From here, we could link a user to download this as an actual file like so:
从这里,我们可以链接用户以将其下载为实际文件,如下所示:
someLink.href = window.URL.createObjectURL(formBlob);
If we wanted this data to persist, we could serialize our blob as a base64 string and save it to localStorage or any other persistent type of storage. Converting blobs to base64 is a bit beyond the scope of this answer but you can find a good reference/library here: http://blog.danguer.com/2011/10/24/base64-binary-decoding-in-javascript/
如果我们希望这些数据持久化,我们可以将 blob 序列化为 base64 字符串并将其保存到 localStorage 或任何其他持久类型的存储中。将 blob 转换为 base64 有点超出本答案的范围,但您可以在这里找到一个很好的参考/库:http: //blog.danguer.com/2011/10/24/base64-binary-decoding-in-javascript/