如何使用JavaScript保存和编辑文件? [英] How to save and edit a file using JavaScript?

查看:184
本文介绍了如何使用JavaScript保存和编辑文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望我的网站用户在文本区域输入一些文本,当他提交表单时,他输入的文本将存储在当前网页的同一目录中的.txt文件中。我并不清楚它是如何完成的,甚至可以用JavaScript来完成。

如何做?

解决方案

是的,HTML5 File API有一个 saveAs 可用于使用Javascript保存二进制数据的API。您可以通过首先将数据放入画布并将其保存为以下格式来生成.txt文件:

  canvas.toBlob(function( blob){
saveAs(blob,filename);
});

看到这个演示,文本文件实际上是在没有PHP的浏览器中生成的。
http://eligrey.com/demos/FileSaver.js/
p>

Eli Gray在2011年由html5rocks撰写了一篇精彩的文章: http://updates.html5rocks.com/2011/08/Saving-generated-files-on-the-client-side

更多阅读W3C:文件管理器界面






修改2016更新



最初的答案显示了一个使用BlobBuilder接口的例子,该接口自已弃用并标记为已过时。现在推荐使用 Blob构造来处理二进制数据。



发布时,Blob构建体支持支持在所有主流浏览器上。 IE 11,Edge 13,Firefox 43,Chrome 45,Safari 9,Opera 35,iOS Safari 8.4,Android Chrome 49.

演示:


  • Koldev发布了jsfiddle如何使用这个新的构造来保存json文件。



更多阅读:


I want a user of my website to enter some text in a text area and when he submits the form, the text that he entered be stored in a .txt file that is present in same directory of the current web page? I don't have a slight idea how it's done or even if it could be done in JavaScript.

How can it be done?

解决方案

Yes you can, HTML5 File API has a saveAs API that can be used to save binary data using Javascript. You can generate a .txt file by first getting the data into a canvas and saving it as:

canvas.toBlob(function(blob) {
  saveAs(blob, filename);
});

See this demo, the text file is actually generated in browser without PHP. http://eligrey.com/demos/FileSaver.js/

There is an excellent article written back in 2011 by Eli Grey on html5rocks: http://updates.html5rocks.com/2011/08/Saving-generated-files-on-the-client-side

More reading at W3C: Filesaver interface


Edit 2016 Update

The original answer showed an example using the BlobBuilder interface which has since been deprecated and marked as obsolete. It is now recommended to use the Blob Construct to manipulate binary data.

At the time of posting, Blob construct is supported on all major browsers. IE 11, Edge 13, Firefox 43, Chrome 45, Safari 9, Opera 35, iOS Safari 8.4, Android Chrome 49.

Demo:

More reading:

这篇关于如何使用JavaScript保存和编辑文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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