How can JavaScript save to a local file?

121,183

Solution 1

Based on http://html5-demos.appspot.com/static/a.download.html:

var fileContent = "My epic novel that I don't want to lose.";
var bb = new Blob([fileContent ], { type: 'text/plain' });
var a = document.createElement('a');
a.download = 'download.txt';
a.href = window.URL.createObjectURL(bb);
a.click();

Modified the original fiddle: http://jsfiddle.net/9av2mfjx/

Solution 2

You should check the download attribute and the window.URL method because the download attribute doesn't seem to like data URI. This example by Google is pretty much what you are trying to do.

Solution 3

It is not possible to save file locally without involving the local client (browser machine) as I could be a great threat to client machine. You can use link to download that file. If you want to store something like Json data on local machine you can use LocalStorage provided by the browsers, Web Storage

Solution 4

It all depends on what you are trying to achieve with "saving locally". Do you want to allow the user to download the file? then <a download> is the way to go. Do you want to save it locally, so you can restore your application state? Then you might want to look into the various options of WebStorage. Specifically localStorage or IndexedDB. The FilesystemAPI allows you to create local virtual file systems you can store arbitrary data in.

Solution 5

So, your real question is: "How can JavaScript save to a local file?"

Take a look at http://www.tiddlywiki.com/

They save their HTML page locally after you have "changed" it internally.

[ UPDATE 2016.01.31 ]

TiddlyWiki original version saved directly. It was quite nice, and saved to a configurable backup directory with the timestamp as part of the backup filename.

TiddlyWiki current version just downloads it as any file download. You need to do your own backup management. :(

[ END OF UPDATE

The trick is, you have to open the page as file:// not as http:// to be able to save locally.

The security on your browser will not let you save to _someone_else's_ local system, only to your own, and even then it isn't trivial.

-Jesse

Share:
121,183

Related videos on Youtube

Mirko Cianfarani
Author by

Mirko Cianfarani

Room: Mirko_Cianfarani @ Miaou My curriculum on Linkedn

Updated on August 22, 2022

Comments

  • Mirko Cianfarani
    Mirko Cianfarani over 1 year

    There's already a solution for writing file JSON online but I want to save json file locally. I've tried to use this example http://jsfiddle.net/RZBbY/10/ It creates a link to download the file, using this call a.attr('href', 'data:application/x-json;base64,' + btoa(t.val())).show(); Is there a way to save the file locally instead of providing a downloadable link? There are other types of conversion beyond data:application/x-json;base64?

    Here's my code:

    <!DOCTYPE html>
    <head> 
        <meta charset="utf-8">
        <title>jQuery UI Sortable - Default functionality</title>
    
        <link rel="stylesheet" href="http://jqueryui.com/themes/base/jquery.ui.all.css">
        <script src="http://jqueryui.com//jquery-1.7.2.js"></script>
        <script src="http://jqueryui.com/ui/jquery.ui.core.js"></script>
        <script src="http://jqueryui.com/ui/jquery.ui.widget.js"></script>
        <script src="http://jqueryui.com/ui/jquery.ui.mouse.js"></script>
        <script src="http://jqueryui.com/ui/jquery.ui.sortable.js"></script>
            <script src="http://jqueryui.com/ui/jquery.ui.accordion.js"></script>
        <link rel="stylesheet" href="http://jqueryui.com/demos/demos.css">        
        <meta charset="utf-8">
        <style>a { font: 12px Arial; color: #ac9095; }</style>
    <script type='text/javascript'>
    $(document).ready(function() {
    var f = $('form'), a = $('a'),
        i = $('input'), t = $('textarea');
           
    $('#salva').click(function() {
        var o = {}, v = t.val();
        
        a.hide();//nasconde il contenuto
        i.each(function() { 
        o[this.name] = $(this).val(); });
        if (v === '') {
            t.val("[\n " + JSON.stringify(o) + " \n]")         
        }
        else {
            t.val(v.substr(0, v.length - 3));
            t.val(t.val() + ",\n " + JSON.stringify(o) +  " \n]")  
        }
    });
    });
    
    $('#esporta').bind('click', function() {
        a.attr('href', 'data:application/x-json;base64,' + btoa(t.val())).show();
            
    });
    </script>
    </head>
    <body>
        <form>
            <label>Nome</label> <input type="text" name="nome"><br />
            <label>Cognome</label> <input type="text" name="cognome">
            <button type="button" id="salva">Salva</button>
        </form>        
    
        <textarea rows="10" cols="60"></textarea><br />
        <button type="button" id="esporta">Esporta dati</button>
        <a href="" style="display: none">Scarica Dati</a>
    </body>
    </html>
    
  • Adil
    Adil almost 12 years
    Thanks, it could be providing wrong information but I did not know this before and used to take help from it. Could be please tell me what is wrong in the particular link I have given in the answer.
  • Mirko Cianfarani
    Mirko Cianfarani almost 12 years
    Thx!!! Now i studying Web storage but There are other types of conversion beyond data:application/x-json;base64?
  • Mirko Cianfarani
    Mirko Cianfarani almost 12 years
    Now I studying Tiddlywiki but There are other types of conversion beyond data:application/x-json;base64?
  • Mirko Cianfarani
    Mirko Cianfarani almost 12 years
    Uao ROdneyrehm I did not know of this site wfools.com
  • Mirko Cianfarani
    Mirko Cianfarani almost 12 years
    thx but There are other types of conversion beyond data:application/x-json;base64?
  • rodneyrehm
    rodneyrehm almost 12 years
    Aside from the fact that it should be application/json - no, I don't see what else would make sense.
  • Mirko Cianfarani
    Mirko Cianfarani almost 12 years
    With IndexedDB how to downloadable local?
  • rodneyrehm
    rodneyrehm almost 12 years
    IndexedDB is not meant to be a downloadable file. It's a database within your browser. It is not what you're looking for.
  • Shanimal
    Shanimal over 11 years
    +1 I've tried data uri schema in the past, it works, but it decides how to name the file you end up with so its pretty much useless. I tried this in Firefox, Safari, Opera and Chrome on Mac, Safari and Opera have no "BlobBuilder" So the disclaimer about "only Chrome dev channel (14.0.835.15+) supports this attribute" is partially true. At this time it works on FireFox, it fails in Safari and Opera.
  • Shanimal
    Shanimal over 11 years
    Blob Builder is supposedly working in MSIE as well... ie.microsoft.com/testdrive/HTML5/BlobBuilder
  • st-boost
    st-boost over 11 years
    tiddlywiki uses a java applet to access the local filesystem, not javascript.
  • dwurf
    dwurf over 11 years
    TiddlyWiki uses a Java applet for Safari and Opera. For IE it uses ActiveX and for Firefox/Camino it uses pure javascript (via privilegeManager) or a firefox extension (since privilegeManager was removed in v15).
  • mahemoff
    mahemoff over 11 years
    This jQuery plugin is extracted from TiddlyWiki, it works how @dwurf explained it. jquery.tiddlywiki.org/twFile.html
  • Ray S.
    Ray S. over 10 years
    is it possible to save everything in the head and body tags using this?
  • Jim Simson
    Jim Simson over 4 years
    This has been my preferred answer.
  • SandPiper
    SandPiper about 3 years
    Link is broken.