1

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?

dda
  • 6,030
  • 2
  • 25
  • 34
U-571
  • 519
  • 2
  • 7
  • 23
  • duplicate? http://stackoverflow.com/questions/8178825/create-text-file-in-javascript – Vinay Jul 20 '13 at 05:15
  • the other way is to use server-side script, e.g. PHP – vladkras Jul 20 '13 at 05:19
  • Why do you want to create a text file. – Rajesh Hegde Jul 20 '13 at 05:19
  • 1
    Why 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. –  Jul 20 '13 at 05: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 Jul 20 '13 at 05:48
  • @Parakrant: if you are only interested in WebKit browsers, this might work: http://stackoverflow.com/questions/7685020/how-to-create-a-text-file-locally-at-client-side-using-javascript-jquery – JayC Jul 20 '13 at 05:52
  • thanks guys for comment. Special thanks to @JayC,@vladkras,@Mike W. Since i am new to web technology. I wanted to know about alternative ideas to implement this kind of problem. – U-571 Jul 21 '13 at 05:22

1 Answers1

3

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
Paul S.
  • 64,864
  • 9
  • 122
  • 138
  • @downvoter please explain why you've down voted this answer; it creates a text file in _JavaScript_ in the client's browser, as requested. – Paul S. Jul 20 '13 at 12:26