Domanda

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.Canvas('c');
data = JSON.stringify(canvas)

My canvas is of fabric js if that helps understanding the problem. I'm just trying to save the canvas as json object and then want to download it as a file so it retains its functionality.

http://jsfiddle.net/P9cEf/3/

jsfiddle, currently its working for online save and load on 2 different canvas I want to download and load from computer.

È stato utile?

Soluzione

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 = new FileReader();
    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 = new Blob([JSON.stringify(canvas1)],{type:'application/json'});
    navigator.msSaveOrOpenBlob(blob, 'data.json');
});

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

Altri suggerimenti

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
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top