32

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.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Praveen
  • 1,781
  • 6
  • 26
  • 32

9 Answers9

42

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() {});
Hgbanana
  • 30
  • 1
  • 4
pimvdb
  • 151,816
  • 78
  • 307
  • 352
  • 1
    when i tried executing this code, i was directed to a link locally. it did not have contents in it. i wanted a text file so i changed the name and followed the instructions on http://www.html5rocks.com/en/tutorials/file/filesystem/ – Praveen Aug 23 '11 at 12:33
  • @Praveen: I missed a few things. Please see my updated code. Does the new fiddle work correctly? – pimvdb Aug 23 '11 at 13:58
  • navigating to a file does not seem to download it. Your example works well but mine navigates to a link and not downloading. – Praveen Aug 23 '11 at 15:17
  • @Praveen: Not sure then; for me it starts downloading `test.bin`. What extension are you using? Perhaps that matters. – pimvdb Aug 23 '11 at 15:27
  • @pimvdb test.bin downloads for me. i was writing a chrome extension that works with facebook. In that, a link for test.bin opens up in facebook but does not download. – Praveen Aug 23 '11 at 16:50
  • @Praveen: I actually meant which extension instead of `.bin`, because `.txt` for example would not download the file but just display it in Chrome itself. But if `.bin` does not start downloading for you I'm not sure what's the reason behind that. Does it also show it inside Chrome, or does nothing happen at all? – pimvdb Aug 23 '11 at 17:16
  • @pimvdb i was using a .txt extension. i need a text file. is there anyway i can get around this. – Praveen Aug 23 '11 at 22:37
  • @pimvdb let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/2785/discussion-between-praveen-and-pimvdb) – Praveen Aug 23 '11 at 22:40
  • 11
    @pimvdb The link is broken – Martin Braun Nov 25 '15 at 13:14
11

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.

RAM
  • 2,413
  • 1
  • 21
  • 33
Tegra Detra
  • 24,551
  • 17
  • 53
  • 78
7

The following method works in IE11+, Firefox 25+ and Chrome 30+:

<a id="export" class="myButton" download="" href="#">export</a>
<script>
    function createDownloadLink(anchorSelector, str, fileName){
        if(window.navigator.msSaveOrOpenBlob) {
            var fileData = [str];
            blobObject = new Blob(fileData);
            $(anchorSelector).click(function(){
                window.navigator.msSaveOrOpenBlob(blobObject, fileName);
            });
        } else {
            var url = "data:text/plain;charset=utf-8," + encodeURIComponent(str);
            $(anchorSelector).attr("download", fileName);               
            $(anchorSelector).attr("href", url);
        }
    }

    $(function () {
        var str = "hi,file";
        createDownloadLink("#export",str,"file.txt");
    });

</script>

See this in Action: http://jsfiddle.net/Kg7eA/

Firefox and Chrome support data URI for navigation, which allows us to create files by navigating to a data URI, while IE doesn't support it for security purposes.

On the other hand, IE has API for saving a blob, which can be used to create and download files.

dinesh ygv
  • 1,840
  • 1
  • 14
  • 18
5

Try this:

document.body.innerHTML+="<a id='test' href='data:text;charset=utf-8,"+encodeURIComponent("hi")+"'>Your Download</a>";
document.getElementById('test').click();

if you want to set the filename use download attribute of anchor tag:

document.body.innerHTML+="<a id='test' href='data:text;charset=utf-8,"+encodeURIComponent("hi")+"' download=yourfilename>Your Download</a>";
document.getElementById('test').click();
Hackaholic
  • 19,069
  • 5
  • 54
  • 72
dsrdakota
  • 2,415
  • 1
  • 15
  • 10
0

No, as that would allow you to create malicious programs in the client's computer, and harm his privacy.

Also, requests to download files come from the server, so you'll need to create the file on the server, and serve it to the user, and hope he'll save it (if he requested for it it's likely that he will).

Another possible solution to look at is to use data URIs or CSVs, but browser support for them is incomplete (IE), see Create a file in memory for user to download, not through server

Community
  • 1
  • 1
Madara's Ghost
  • 172,118
  • 50
  • 264
  • 308
0

You will need server side functionality in order to server the user a text file (javascript is not enough). You can create a server side script that creates the file and use javascript in order to prompt user to save it.

nonouco
  • 1,170
  • 1
  • 13
  • 25
0

On Submit button from user, you can create file on server and redirect user to url of the file, from where it should get automatically downloaded.

vicky
  • 885
  • 1
  • 7
  • 23
  • Automatically downloaded? Says who? – Delan Azabani Aug 23 '11 at 12:12
  • i mean at server end, after saving file at server and redirect user to the url which points to the file (www.domain.com/abc.txt), then it will automatically prompt user to save file at client side.... – vicky Aug 23 '11 at 13:16
-1
var isIE = /*@cc_on!@*/ false || !! document.documentMode; // At least IE6
var uri = "some data"; //data in file
var fileName = "file.i4cvf"; // any file name with any extension
if (isIE) {
    var fileData = ['\ufeff' + uri];
    var blobObject = new Blob(fileData);
    window.navigator.msSaveOrOpenBlob(blobObject, fileName);
} else //chrome
{
    window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;
    window.requestFileSystem(window.TEMPORARY, 1024 * 1024, function (fs) {
        fs.root.getFile(fileName, {
            create: true
        }, function (fileEntry) {
            fileEntry.createWriter(function (fileWriter) {
                var fileData = ['\ufeff' + uri];
                var blob = new Blob(fileData);
                fileWriter.addEventListener("writeend", function () {
                    var fileUrl = fileEntry.toURL();
                    var link = document.createElement('a');
                    link.href = fileUrl;
                    link.download = fileName;
                    document.body.appendChild(link);
                    link.click();
                    document.body.removeChild(link);
                }, false);
                fileWriter.write(blob);
            }, function () {});
        }, function () {});
    }, function () {});
}
Sebastian Brosch
  • 42,106
  • 15
  • 72
  • 87
-1

This link helped me a lot and solved my problem. Cross browser solution:

https://www.thewebflash.com/reading-and-creating-text-files-using-the-html5-file-api/

This is the most relevant part:

if ('msSaveOrOpenBlob' in navigator) {

    navigator.msSaveOrOpenBlob(textFileAsBlob, fileName);
} else {
    var downloadLink = document.createElement('a');
    downloadLink.download = fileName;
    downloadLink.innerHTML = 'Download File';
    if ('webkitURL' in window) {
        // Chrome allows the link to be clicked
        // without actually adding it to the DOM.
        downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob);
    } else {
        // Firefox requires the link to be added to the DOM
        // before it can be clicked.
        downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
        downloadLink.onclick = destroyClickedElement;
        downloadLink.style.display = 'none';
        document.body.appendChild(downloadLink);
    }

    downloadLink.click();
}
cezar
  • 11,616
  • 6
  • 48
  • 84
giablu82
  • 1
  • 1
  • A link to a solution is welcome, but please ensure your answer is useful without it: [add context around the link](//meta.stackexchange.com/a/8259) so your fellow users will have some idea what it is and why it’s there, then quote the most relevant part of the page you're linking to in case the target page is unavailable. [Answers that are little more than a link may be deleted.](//stackoverflow.com/help/deleted-answers) – Baum mit Augen Jan 16 '18 at 10:01