[javascript] How can JavaScript save to a local file?

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>

This question is related to javascript jquery json jsonp

The answer is


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.


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/


While most despise Flash, it is a viable option for providing "save" and "save as" functionality in your html/javascript environment.

I've created a widget called "OpenSave" that provides this functionality available here:

http://www.gieson.com/Library/projects/utilities/opensave/

-mike


If you are using FireFox you can use the File HandleAPI

https://developer.mozilla.org/en-US/docs/Web/API/File_Handle_API

I had just tested it out and it works!


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


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


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.


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to json

Use NSInteger as array index Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) HTTP POST with Json on Body - Flutter/Dart Importing json file in TypeScript json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190) Angular 5 Service to read local .json file How to import JSON File into a TypeScript file? Use Async/Await with Axios in React.js Uncaught SyntaxError: Unexpected token u in JSON at position 0 how to remove json object key and value.?

Examples related to jsonp

CORS header 'Access-Control-Allow-Origin' missing JSONP call showing "Uncaught SyntaxError: Unexpected token : " jquery.ajax Access-Control-Allow-Origin Parse JSON response using jQuery parsing JSONP $http.jsonp() response in angular.js How can JavaScript save to a local file? Javascript search inside a JSON object IE9 jQuery AJAX with CORS returns "Access is denied" jquery how to use multiple ajax calls one after the end of the other Callback function for JSONP with jQuery AJAX