Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a file using Javascript in Chrome on client side

I would like to know if I can create a text file and save the file in the users "Downloads" section in his/her computer using Javascript. The way my feature should work is when the user clicks the submit button, I populate the users info in the text file and then save it in his machine. I would like this to work in Google Chrome.

Is this possible? I have seen posts that specifically tell me that it is a serious security issue.

like image 428
Praveen Avatar asked Aug 23 '11 12:08

Praveen


People also ask

Can JavaScript create a file?

Did you know you can create files using JavaScript right inside your browser and have users download them? You can create files with a proper name and mime type and it only takes a few lines of code.

Can Chrome extensions write files?

(Chrome OS only) Extends Chrome. For example, apps or extensions can allow users to upload files to a website. Allows app or extension to create, read, navigate, and write to the user's local file system at a user-selected location.

Can JavaScript write to disk?

The short answer is no; you cannot by default write a file to the local disk, by using plain JavaScript in a browser. You'll need a helper to do that. For example, TiddlyWiki is a wiki engine that is just a single, static HTML file, but it can write itself to disk with the help of a Java applet (Tiddly Saver).


2 Answers

Sure you can, using the brand new APIs.

 window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;   window.requestFileSystem(window.TEMPORARY, 1024*1024, function(fs) {     fs.root.getFile('test.bin', {create: true}, function(fileEntry) { // test.bin is filename         fileEntry.createWriter(function(fileWriter) {             var arr = new Uint8Array(3); // data length              arr[0] = 97; // byte data; these are codes for 'abc'             arr[1] = 98;             arr[2] = 99;              var blob = new Blob([arr]);              fileWriter.addEventListener("writeend", function() {                 // navigate to file, will download                 location.href = fileEntry.toURL();             }, false);              fileWriter.write(blob);         }, function() {});     }, function() {}); }, function() {}); 
like image 60
pimvdb Avatar answered Sep 30 '22 16:09

pimvdb


Enter this into the Chrome browser

data:text;charset=utf-8,helloWorld 

So to construct the download for your users you would do something like

data='<a href='data:text;charset=utf-8,'+uriEncode(yourUSERdataToDownload)+' >Your Download</a>

Then inject it into the dom for your user to press.

like image 41
James Andino Avatar answered Sep 30 '22 18:09

James Andino