Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
269 views
in Technique[技术] by (71.8m points)

html - How to save and edit a file using JavaScript?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

My 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:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...