U-571
U-571

Reputation: 517

Creation of a text file from Javascript (or any other way) on the client side?

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?

Upvotes: 1

Views: 253

Answers (1)

Paul S.
Paul S.

Reputation: 66404

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

Upvotes: 3

Related Questions