【发布时间】:2020-06-07 14:07:29
【问题描述】:
我有一个网络应用程序,用户可以使用 html5 FileReader API 选择本地文件作为输入。有什么方法可以检查文件是否已更改,在现代浏览器中有效?
从历史上看,这在某些浏览器中是可能的,方法是轮询文件对象并比较 File.lastModifiedDate(已弃用)或 File.lastModified 属性,如本 QA 中所述:Check if file has changed using HTML5 File API。但是,规范说lastModifiedDate 和其他文件数据应该是文件的快照,就像用户第一次选择它时的样子,所以这应该不起作用(而且似乎大多数浏览器的最新版本确实遵循规范现在,使这个 hack 不可用)。
我希望能够通过读取文件来检查更改。这种方法可行,但只要文件在磁盘上发生更改,Chrome 和 Firefox 就会抛出错误,提示 DOMException: The requested file could not be read, typically due to permission problems that have occurred after a reference to a file was acquired. 有什么办法解决这个问题吗?
这是我尝试过的:
let oldText
setInterval(function () {
const fileObj = document.getElementById('myFileInput').files[0]
const reader = new FileReader()
reader.onload = evt => {
const text = evt.target.result
if (text !== oldText) {
console.log("The file has changed!")
oldText = text
}
}
reader.readAsText(fileObj)
}, 1000)
...或更简单:
const fileObj = document.getElementById('myFileInput').files[0]
const reader = new FileReader()
reader.readAsText(fileObj) // works
// now lets edit the file and try again
reader.readAsText(fileObj) // fails
reader.readAsText() 按预期工作,直到文件被更改,当它抛出上述错误时。我想这是一种安全措施,尽管我不完全理解它试图保护用户免受什么伤害。我能做些什么呢?
【问题讨论】:
-
这是一种安全措施。你无能为力。
-
在选择后文件更改时禁止读取的规范部分是here。
标签: javascript filereader fileapi