如何以编程方式在Javascript中创建可由用户下载的客户端文件? [英] How to programmatically create a client side file in Javascript that can be downloaded by the user?

查看:119
本文介绍了如何以编程方式在Javascript中创建可由用户下载的客户端文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想尝试创建一个Javascript应用程序,该应用程序从表单中获取用户的输入,然后根据用户的表单输入生成文件。

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.

该文件应该然后用户可以下载所有内容而无需触及服务器。

The file should then be downloadable by the user all without touching the server.

如何使用JavaScript在客户端创建文件,以及在客户端如何存储文件它可以在没有首先在服务器上创建的情况下下载吗?

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?

更新:更具体,正如格雷厄姆回答的那样,我一直在寻找创建文件的方法而不必触及文件系统本身,但只是创建一个可由用户下载的文件对象(Blob)。谢谢格雷厄姆!

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!

推荐答案

在不使用文件系统的情况下执行此操作的一种方法是创建blob。假设我们有一堆数据(在您的情况下,来自表单),我们希望将其保存为文本文件。我们实际上可以做如下事情:

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:

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);

如果我们希望这些数据保持不变,我们可以将blob序列化为base64字符串并将其保存到localStorage或任何其他持久存储类型。将blob转换为base64有点超出了这个答案的范围,但你可以在这里找到一个好的参考/库: http://blog.danguer.com/2011/10/24/base64-binary-decoding-in-javascript/

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/

这篇关于如何以编程方式在Javascript中创建可由用户下载的客户端文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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