【问题标题】:Check if local file has changed [duplicate]检查本地文件是否已更改[重复]
【发布时间】: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


【解决方案1】:

如果/当Native File System API 在浏览器中实现时,这将再次成为可能。在计划于 2020 年 10 月发布的 Google Chrome 85 中,它将是 partially enabled

与 FileReader API 不同,它需要显式的用户交互,因此您可以这样做:

myFileInput.addEventListener('change', async (e) => {
  const fh = await window.chooseFileSystemEntries()
  // fh is now a FileSystemFileHandle object
  // Use fh.getFile() to get a File object
})

【讨论】:

  • Chrome,是的,这也可能意味着 Edge (> v44),但它目前对于 Firefox 看起来不太好,对于 Safari 来说也不可能是 this。 :-|
猜你喜欢
  • 2018-09-13
  • 2012-09-21
  • 2013-06-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-17
  • 2019-04-16
  • 1970-01-01
相关资源
最近更新 更多