Skip to content Skip to sidebar Skip to footer

How To Download Json Object As File From Browser

I have a json object, can I save it as a file on my desktop if yes how to do that and how to read that file back. I am working in javascript and html only. var canvas = new fabric.

Solution 1:

You can make use of the download attribute of the anchor tag(I don't know how well supported it is) and the html5 file api.

<a href = "#"id = "save" download="data.json">Save Canvas 1</a>
Load Canvas<input type="file"id="load" />
$( "#save" ).click(function( event ) {
    this.href = 'data:plain/text,' + JSON.stringify(canvas1)
});
$( "#load" ).change(function( event ) {
    var fr = newFileReader();
    fr.onload = function(){
        canvas2.loadFromJSON(this.result, canvas2.renderAll.bind(canvas2));
    }
    fr.readAsText(this.files[0]);    
});

http://jsfiddle.net/P9cEf/5/


Here is a version or new IE (IE11 at least)

$( "#save" ).click(function( event ) {
    event.preventDefault();
    var blob = newBlob([JSON.stringify(canvas1)],{type:'application/json'});
    navigator.msSaveOrOpenBlob(blob, 'data.json');
});

http://jsfiddle.net/P9cEf/7/

Solution 2:

Save

Update your save function to use this snippet to save the file to desktop:

Upload

  • And then you would just need a form and server to upload to so that you can process a person's file they upload to a temporary location on the server, to load into your function that you already have made.
  • What is available to you for server-side programming languages? Just Google how to upload a file in that language
  • You can get contents of that file once it's uploaded via XHR request using jQuery ajax or vanilla JavaScript

Post a Comment for "How To Download Json Object As File From Browser"