I want to create a text file from Javascript. The user will submit a form, the form will have multiple choices. The user will select the appropriate answers and click on submit button. Now these answers will be put in that text file. For designing this, I have created the HTML file. Now I have a problem with the Javascript. Please tell me, is there any other way instead of JavaScript?
-
duplicate? stackoverflow.com/questions/8178825/…Vinay– Vinay2013-07-20 05:15:18 +00:00Commented Jul 20, 2013 at 5:15
-
the other way is to use server-side script, e.g. PHPvladkras– vladkras2013-07-20 05:19:07 +00:00Commented Jul 20, 2013 at 5:19
-
Why do you want to create a text file.Rajesh Hegde– Rajesh Hegde2013-07-20 05:19:23 +00:00Commented Jul 20, 2013 at 5:19
-
1Why do you need the text file? Is it just to provide some persistence, or will there be other content? For persistence you can use localStorage or the filesystem API. If you're trying to provide a document that the user can access outside the browser you will have to send it via a server.user1864610– user18646102013-07-20 05:20:54 +00:00Commented Jul 20, 2013 at 5:20
-
@Vinay: I'm not sure that the answers on that one are that great or current. I figure if there's not a better question more recent it might be worth the revisit.JayC– JayC2013-07-20 05:48:05 +00:00Commented Jul 20, 2013 at 5:48
|
Show 2 more comments
1 Answer
With a String of whatever text you want
var str = 'Hello world!';
1. Create a Blob with MIME type of text/plain
var b = new Blob([str], {type: 'text/plain'});
2. Generate a URL from your Blob
var fileURL = URL.createObjectURL(b);
3. Point your user to it in your favourite way, e.g.
window.open(fileURL, '_blank');
OR, if you want to download this
var a = document.createElement('a'),
e = document.createEvent("MouseEvents"); // simulated click
e.initMouseEvent("click", true, false, self,
0, 0, 0, 0, 0, false, false, false, false, 0, null);
a.setAttribute('href', fileURL);
a.setAttribute('target', '_blank'); // fallback behaviour
a.setAttribute('download', 'myTextFile.txt'); // file name
a.dispatchEvent(e); // download
1 Comment
Paul S.
@downvoter please explain why you've down voted this answer; it creates a text file in JavaScript in the client's browser, as requested.