我有一个本地程序,它将 JSON 对象写入文件,以便 JavaScript 可以获取其数据并处理它。使用 <input>
选择文件对象:
<form id = "getfiles">
<input type = "file" multiple id = "files" />
</form>
具有以下 JS 函数 setInterval
每 300 毫秒重复一次。但是,当文件发生更改时,只有 Google Chrome 会重新加载文件并处理新内容;我必须在 IE 10 和 Firefox 20 中手动重新选择页面上的文件。
function speakText()
{
var thefile = document.getElementById('files').files[0];
var lastChanged = thefile.lastModifiedDate;
var reader = new FileReader();
reader.onload = function(event)
{
var lcd = document.getElementById("last_change_date");
if (!lcd)
{
var spanLastChanged = document.createElement("span");
spanLastChanged.id = "last_change_date";
spanLastChanged.innerText = lastChanged;
console.log(lastChanged);
document.body.appendChild(spanLastChanged);
}
else
{
// compare lastChanged with last_change_date
var last_known_change = Date.parse(lcd.innerText);
// var last_known_change = Date.parse(thefile.lastModifiedDate);
if (last_known_change !== Date.parse(lastChanged))
{
console.log("Something is new since " + lcd.innerText);
var fileContent = event.target.result;
var commands = JSON.parse(fileContent);
handleJSON(fileContent);
lcd.innerText = lastChanged;
}
}
}
reader.readAsText(thefile, "UTF-8");
}
最佳答案
Firefox 和 IE 按照规范做了正确的事情:与文件输入关联的 File 对象应该是创建 File 对象时文件的不可变快照。 WebKit/Blink 中的一个已知错误是它们仅存储对文件数据的引用,因此更改数据将更改 File 对象所看到的内容。
事实上,WebKit/Blink 行为是一个隐私错误:当用户在文件输入中选择一个文件时,他们会授予网页读取该文件数据的权限当时,不适用于该文件的所有 future 版本!这就是规范按原样编写的原因。
关于javascript - 文件输入不会更新(Chrome 除外),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17779621/