JS FileReader API在Firefox中的行为不同于在Chrome中的行为。将使用FileReader的文件放入一个间隔(在Firefox中)后,更新后就不会读取该文件。这是由于Firefox缓存上传的文件,因此没有间隔重新读取文件吗?在Chrome中不会发生此问题。
我正在构建一个实用程序,将自定义CSS加载到HTML的样式标签中。我尝试将FileReader实例化和onload函数放置在间隔内以每次创建一个新实例-似乎不起作用。
HTML
<p>Hello</p>
<input id="files" type="file">
<div>
<code class="output"></code>
</div>
JavaScript
const fileReader = new FileReader(); // FileReader instance
fileReader.onload = function () {
// once the result is resolved, run the output function
if (fileReader.result) outputToUI(fileReader.result);
};
const textOutput = document.querySelector('.output'); // where the file contents go
setInterval(() => {
let files = [];
if (document.querySelector('#files')) {
files = document.querySelector('#files').files; // grab the FileList => [Array]
files.length !== 0 ? readText(files) : null; // if there's at least one file, read the text
}
}, 1000);
function outputToUI(text) {
textOutput.innerText = ''; // empty out text
textOutput.innerText = text; // replace with new text
}
function readText(fileList) {
if (fileList && fileList[0]) {
fileReader.readAsText(fileList[0]); // read the file as text => FileReader.result
}
}
预期行为的示例如下:
|> interval is made and starts looking for files
=> null
|> user uploads a file (styles.css)
=> body { box-sizing: border-box; }
|> user updates a property and saves the same file (styles.css)
=> body { box-sizing: border-box; margin: 0; }
// still returns "body { box-sizing: border-box; }" in Firefox