JavaScript 如何保存到本地文件?

新手上路,请多包涵

已经有在线写入文件JSON的解决方案,但我想在本地保存json文件。我试过使用这个例子 http://jsfiddle.net/RZBbY/10/ 它创建了一个链接来下载文件,使用这个调用 a.attr('href', 'data:application/x-json;base64,' + btoa(t.val())).show(); 有没有办法在本地保存文件而不是提供下载链接?除了 data:application/x-json;base64 之外还有其他类型的转换吗?

这是我的代码:

 <!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>

原文由 Mirko Cianfarani 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 451
1 个回答

基于 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();

修改了原来的fiddle:http: //jsfiddle.net/9av2mfjx/

原文由 Stanislav 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题