简体   繁体   English

JavaScript 如何保存到本地文件?

[英]How can JavaScript save to a local file?

There's already a solution for writing file JSON online but I want to save json file locally.已经有在线写入文件 JSON 的解决方案,但我想在本地保存 json 文件。 I've tried to use this example http://jsfiddle.net/RZBbY/10/ It creates a link to download the file, using this call a.attr('href', 'data:application/x-json;base64,' + btoa(t.val())).show();我尝试使用这个例子http://jsfiddle.net/RZBbY/10/它创建一个链接来下载文件,使用这个调用a.attr('href', 'data:application/x-json;base64,' + btoa(t.val())).show(); Is there a way to save the file locally instead of providing a downloadable link?有没有办法在本地保存文件而不是提供可下载的链接? There are other types of conversion beyond data:application/x-json;base64 ?除了data:application/x-json;base64之外还有其他类型的转换吗?

Here's my code:这是我的代码:

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

You should check the download attribute and the window.URL method because the download attribute doesn't seem to like data URI. 您应该检查download属性和window.URL方法,因为download属性似乎不喜欢数据URI。 This example by Google is pretty much what you are trying to do. Google的这个示例几乎就是您想要做的。

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 如果要在本地计算机上存储诸如Json数据之类的内容,则可以使用浏览器提供的LocalStorageWeb Storage

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. 那么<a download>是解决之道。 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 . 然后,您可能需要研究WebStorage的各种选项。 Specifically localStorage or IndexedDB . 特别是localStorageIndexedDB The FilesystemAPI allows you to create local virtual file systems you can store arbitrary data in. FilesystemAPI允许您创建可以存储任意数据的本地虚拟文件系统。

While most despise Flash, it is a viable option for providing "save" and "save as" functionality in your html/javascript environment. 尽管大多数人鄙视Flash,但它是在html / javascript环境中提供“保存”和“另存为”功能的可行选择。

I've created a widget called "OpenSave" that provides this functionality available here: 我创建了一个名为“ OpenSave”的小部件,可在此处提供此功能:

http://www.gieson.com/Library/projects/utilities/opensave/ http://www.gieson.com/Library/projects/utilities/opensave/

-mike -麦克风

So, your real question is: "How can JavaScript save to a local file?" 因此,您真正的问题是:“如何将JavaScript保存到本地文件?”

Take a look at http://www.tiddlywiki.com/ 看看http://www.tiddlywiki.com/

They save their HTML page locally after you have "changed" it internally. 在内部进行“更改”后,他们会将HTML页面保存在本地。

[ UPDATE 2016.01.31 ] [更新2016.01.31]

TiddlyWiki original version saved directly. TiddlyWiki的原始版本直接保存。 It was quite nice, and saved to a configurable backup directory with the timestamp as part of the backup filename. 这非常不错,并以时间戳记作为备份文件名的一部分保存到可配置的备份目录中。

TiddlyWiki current version just downloads it as any file download. TiddlyWiki当前版本只是将其下载为任何文件。 You need to do your own backup management. 您需要执行自己的备份管理。 :( :(

[ END OF UPDATE [更新结束

The trick is, you have to open the page as file:// not as http:// to be able to save locally. 诀窍是,您必须以file://而不是以http://的形式打开页面才能保存在本地。

The security on your browser will not let you save to _someone_else's_ local system, only to your own, and even then it isn't trivial. 浏览器上的安全性不会让您保存到_someone_else的_本地系统中,而只能保存到自己的本地系统中,即使如此,它也不是一件容易的事。

-Jesse -杰西

Based on http://html5-demos.appspot.com/static/a.download.html : 基于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/ 修改了原始小提琴: http : //jsfiddle.net/9av2mfjx/

If you are using FireFox you can use the File HandleAPI 如果您使用的是FireFox,则可以使用File HandleAPI

https://developer.mozilla.org/en-US/docs/Web/API/File_Handle_API https://developer.mozilla.org/zh-CN/docs/Web/API/File_Handle_API

I had just tested it out and it works! 我刚刚对其进行了测试,并且可以正常工作!

The possible ways to create and save files in Javascript are:在 Javascript 中创建和保存文件的可能方法是:

Use a library called FileSaver使用名为 FileSaver 的库

saveAs(new File(["CONTENT"], "demo.txt", {type: "text/plain;charset=utf-8"}));

Create a blob object and offer a “save as”.创建一个 blob 对象并提供“另存为”。

var a = document.createElement("a");
a.href = window.URL.createObjectURL(new Blob(["CONTENT"], {type: "text/plain"}));
a.download = "demo.txt";
a.click();

Upload the data, save it on the server.上传数据,保存在服务器上。

var data = new FormData();
data.append("upfile", new Blob(["CONTENT"], {type: "text/plain"}));
fetch("SERVER.SCRIPT", { method: "POST", body: data });

Create a writable file stream.创建可写文件流。

const fileHandle = await window.showSaveFilePicker();
const fileStream = await fileHandle.createWritable();
await fileStream.write(new Blob(["CONTENT"], {type: "text/plain"}));
await fileStream.close();

In NodeJS, simply use the file system module在 NodeJS 中,只需使用文件系统模块

 require("fs").writeFile("demo.txt", "Foo bar!");

<!-- (A) LOAD FILE SAVER -->
<!-- https://cdnjs.com/libraries/FileSaver.js -->
<!-- https://github.com/eligrey/FileSaver.js -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2.0.5/FileSaver.min.js"></script>
 
<script>
// (B) "SAVE AS"
var myFile = new File(["CONTENT"], "demo.txt", {type: "text/plain;charset=utf-8"});
saveAs(myFile);
</script>

// (A) CREATE BLOB OBJECT
var myBlob = new Blob(["CONTENT"], {type: "text/plain"});

// (B) CREATE DOWNLOAD LINK
var url = window.URL.createObjectURL(myBlob);
var anchor = document.createElement("a");
anchor.href = url;
anchor.download = "demo.txt";
    
// (C) "FORCE DOWNLOAD"
// NOTE: MAY NOT ALWAYS WORK DUE TO BROWSER SECURITY
// BETTER TO LET USERS CLICK ON THEIR OWN
anchor.click();
window.URL.revokeObjectURL(url);
document.removeChild(anchor);

    <script>
    function blobajax () {
      // (A) CREATE BLOB OBJECT
      var myBlob = new Blob(["CONTENT"], {type: "text/plain"});
    
      // (B) FORM DATA
      var data = new FormData();
      data.append("upfile", myBlob);
    
      // (C) AJAX UPLOAD TO SERVER
      fetch("3b-upload.php", {
        method: "POST",
        body: data
      })
      .then((res) => { return res.text(); })
      .then((txt) => { console.log(txt); });
    }
    </script>
    <input type="button" value="Go" onclick="blobajax()"/>

    <script>
    async function saveFile() {
      // (A) CREATE BLOB OBJECT
      var myBlob = new Blob(["CONTENT"], {type: "text/plain"});
     
      // (B) FILE HANDLER & FILE STREAM
      const fileHandle = await window.showSaveFilePicker({
        types: [{
          description: "Text file",
          accept: {"text/plain": [".txt"]}
        }]
      });
      const fileStream = await fileHandle.createWritable();
     
      // (C) WRITE FILE
      await fileStream.write(myBlob);
      await fileStream.close();
    }
    </script>
    
    <input type="button" value="Save File" onclick="saveFile()"/>

// (A) LOAD FILE SYSTEM MODULE
// https://nodejs.org/api/fs.html
const fs = require("fs");

// (B) WRITE TO FILE
fs.writeFile("demo.txt", "CONTENT", "utf8", (error, data) => {
  console.log("Write complete");
  console.log(error);
  console.log(data);
});

/* (C) READ FROM FILE
fs.readFile("demo.txt", "utf8", (error, data) => {
  console.log("Read complete");
  console.log(error);
  console.log(data);
});
*/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Javascript:如何将文件位置保存到本地存储? - Javascript: How to save file location to local storage? 在本地计算机上:如何使用Javascript和ActiveX下载和保存文件? - On a local machine: How can I download and save a file using Javascript and ActiveX? 如何使用javascript中的Blob创建文件并将其保存在本地系统中? - How can i create a file and save it in local system using Blob in javascript? 我如何*本地*保存由javascript生成的.html文件(在* local * .html页面上运行)? - How can I *locally* save an .html file generated by javascript (running on a *local* .html page)? 如何使用javascript将数组缓冲区保存到磁盘上的本地文件 - How to save an array buffer to a local file on disk using javascript 在javascript中,如何将用户输入保存到本地目录中的文件 - In javascript, how to user inputs save to a file to a local directory 你好,我怎样才能将这些值保存在本地存储中? (Javascript) - hello, how can i save these values ​in a local storage? (Javascript) 如何在 QT 中将 JSON 保存到本地文本文件? - How can I save JSON to local text file in QT? 在Javascript中从本地数据保存文件 - Save File From Local Data in Javascript 将Javascript文件对象保存到本地存储 - Save Javascript file object to local storage
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM