Praveen Praveen - 4 years ago 314
Javascript Question

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.

Answer Source

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);

        }, function() {});
    }, function() {});
}, function() {});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download