如何从浏览器下载json对象作为文件 [英] how to download json object as file from browser

查看:1697
本文介绍了如何从浏览器下载json对象作为文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个json对象,我可以将它保存为我的桌面上的文件,如果是的话怎么做以及如何读取该文件。我只在javascript和html中工作。

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)

我的画布是面料js如果有帮助的话了解问题。我只是想将画布保存为json对象,然后将其作为文件下载,以便保留其功能。

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,目前它工作在线保存和加载2个不同的画布我想下载并从计算机加载。

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

推荐答案

你可以利用锚标签的下载属性(我不知道它支持得多好)和html5文件api。

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/

这是一个版本或新IE(至少IE11)

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/

这篇关于如何从浏览器下载json对象作为文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆