1. html代码
<input type="file" id="fileInput" accept=".txt" />
<pre id="content"></pre>
2. js逻辑代码
const fileInput = document.getElementById('fileInput');
const contentElement = document.getElementById('content');
// 尝试从缓存加载内容
const cachedContent = window.localStorage.getItem('cachedTextFile');
console.log(cachedContent, 'cachedContent')
if (cachedContent) {
contentElement.textContent = cachedContent;
}
// 用户选择新文件时更新缓存
fileInput.addEventListener('change', (e) => {
const file = e.target.files[0];
if (!file) return;
const reader = new FileReader();
reader.onload = (e) => {
const text = e.target.result;
contentElement.textContent = text;
window.localStorage.setItem('cachedTextFile', text); // 保存到缓存
};
reader.readAsText(file);
});
4. 演示效果