How can JavaScript save to a local file?

后端 未结 7 1298
渐次进展
渐次进展 2020-12-29 08:27

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 lin

相关标签:
7条回答
  • 2020-12-29 09:06

    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

    0 讨论(0)
  • 2020-12-29 09:11

    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.

    0 讨论(0)
  • 2020-12-29 09:12

    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/

    0 讨论(0)
  • 2020-12-29 09:20

    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!

    0 讨论(0)
  • 2020-12-29 09:23

    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

    0 讨论(0)
  • 2020-12-29 09:25

    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.

    0 讨论(0)
提交回复
热议问题