javascript中的文件写操作

时间:2015-09-01 08:30:18

标签: javascript

我需要在javascript中写入一个文件。我试过Code.I得到错误,如#34; FileWriter没有定义"。请帮助我。

<html>
<head>

</head>
<body>
 <input type = "button" value = "write" onclick="WriteFile()">
<script>

function WriteFile()
{
var fileWriter = new FileWriter("C:\Users\ananthi\Desktop\readme.txt");
fileWriter.open() ; 
fileWriter.writeLine("Another line") ; 
fileWriter.close() ;

}


</script>
</body>
</html>

2 个答案:

答案 0 :(得分:2)

File Writer API已经不存在,从未见过重要的浏览器支持。

您无法从基于浏览器的JavaScript编写文件。您所做的是为用户提供他们可以下载的链接,如下所示:

var filename = "readme.txt";
var text = "Text of the file goes here.";
var blob = new Blob([text], {type:'text/plain'});
var link = document.createElement("a");
link.download = filename;
link.innerHTML = "Download File";
link.href = window.URL.createObjectURL(blob);
document.body.appendChild(link);

适用于支持File APImodern ones do但不支持IE9或更早版本)的浏览器。

答案 1 :(得分:0)

如果您想使用按钮调用功能:

<input type = "button" value = "write" onclick="Download()">

Download () {
        let filename = "readme.txt";
        let text = "Text of the file goes here.\n1";
        let blob = new Blob([text], {type:'text/plain'});
        let link = document.createElement("a");
        link.download = filename;
        //link.innerHTML = "Download File";
        link.href = window.URL.createObjectURL(blob);
        document.body.appendChild(link);
        link.click();
        setTimeout(() => {
            document.body.removeChild(link);
            window.URL.revokeObjectURL(link.href);
        }, 100);
    }