简体   繁体   English

如何使用javascript将数据写入文件?

[英]How to write data to a file using javascript?I

I know by default this is not allowed , can you help me how to change the security settings so that i can write to a file. 我知道默认情况下这是不允许的,您能帮我如何更改安全设置,以便我可以写入文件。 thank you 谢谢

there is absolutely no way to write to a file with a browser. 绝对没有办法使用浏览器写入文件。 but modern browsers like Chrome allow you to create files on the fly 但是现代浏览器(例如Chrome)允许您即时创建文件

In this example i add a textarea to the document. 在此示例中,我向文档添加了文本区域。

this has a eventlistener onchange.(so write something and blur it clicking outside) 这有一个eventlistener onchange。(所以写点东西,然后在外面单击使其模糊)

onchange it reads the value of your textarea and converts it into base64 onchange它读取您的textarea的值并将其转换为base64

which is easely done with btoa() 使用btoa()轻松完成

the data is added to the href of a new created anchor which is prefixed with (text/plain) as mimetype and data: telling the browser that it's a DATA STRING and not a link. 数据会添加到新创建的锚的href中,该锚的前缀为(text / plain)作为模仿类型和数据:告诉浏览器这是数据字符串,而不是链接。

Chrome also has a new attribute called download on anchors. Chrome浏览器还具有一个称为“锚点download的新属性。 which is basically the filename. 这基本上是文件名。

this is the fastest and easiest way in modern browsers to create a file clientside.. 这是现代浏览器中创建文件客户端的最快,最简单的方法。

you just have to click to download it. 您只需单击即可下载。

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>write to file</title>
</head>
<body>
<script>
var t=document.createElement('textarea');
t.addEventListener('change',function(){
 var a=document.createElement('a');
 a.download='text.txt';
 a.innerText='download';
 a.href='data:text/plain;base64,'+btoa(this.value);
 document.body.appendChild(a);
},false)
document.body.appendChild(t);
</script>
</body>
</html>

another solution is to use the also modern browser only window.filesystem which stores the files you want in a virtual chrome cache(temporany or persistant). 另一个解决方案是使用也仅是现代浏览器的window.filesystem ,它将所需的文件存储在虚拟chrome缓存中(临时或持久性)。 Filesystem can store big files as blobs and it uses low resources. 文件系统可以将大文件存储为Blob,并且使用的资源较少。

then there is localstorage/indexedDB/websql for tiny files. 然后有用于小文件的localstorage / indexedDB / websql。

in the last solution you need to save your data as base64 else you can'tstore your info. 在最后一个解决方案中,您需要将数据另存为base64,否则您将无法存储信息。

in all of the solutions you have the files in your browser,you need a modern browser....but you need to download the file. 在所有解决方案中,您的浏览器中都有文件,您需要现代的浏览器....但是您需要下载文件。

if you want to write data on a already existing file you can use FileReadr() with FileWriter.append() and drag & drop or just a simple file input to select the existing file. 如果要在现有文件上写入数据,则可以将FileReadr()FileWriter.append()然后拖放或仅输入一个简单的文件来选择现有文件。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM