无需用户输入,通过JavaScript利用查询字符串加载并显示文本文件
问题修复方案
你的代码有三个关键问题导致无法正常显示文件内容:
- 获取文件输入框的文件列表时,错误使用了
.file属性,正确的属性是**.files** - 页面中缺少用于展示文件内容的
.content元素 FileReader没有绑定onload事件,无法将读取到的内容渲染到页面
以下是修正后的完整代码:
<html> <head> <title>reading file</title> </head> <body> <input type="file" onchange="previewFile()" /> <input name="Button1" type="button" value="button" onclick="previewFile()"/> <!-- 添加用于显示内容的元素 --> <div class="content"></div> <script> const filename = "textfile.txt" // 模拟查询字符串传入的文件名 const fileInput = document.querySelector('input[type="file"]'); // 创建模拟文件 const myFile = new File(['Hello World!'], filename, { type: 'text/plain', lastModified: new Date(), }); const dataTransfer = new DataTransfer(); dataTransfer.items.add(myFile); fileInput.files = dataTransfer.files; previewFile(); </script> <script> function previewFile() { const contentEl = document.querySelector('.content'); // 修正:使用.files属性获取文件列表 const [file] = document.querySelector('input[type=file]').files; const reader = new FileReader(); if (file) { reader.readAsText(file); // 绑定onload事件,读取完成后渲染内容 reader.onload = function(e) { contentEl.textContent = e.target.result; }; } } </script> </body> </html>
关键修改说明
- 修复文件列表获取:把
.file改为.files,这样才能正确解构出选中的文件对象 - 添加内容容器:新增
<div class="content"></div>作为文件内容的展示区域 - 绑定FileReader加载事件:通过
reader.onload监听文件读取完成事件,将读取到的文本内容赋值给内容容器的textContent属性
内容的提问来源于stack exchange,提问作者jim barnes
相关产品推荐
相关产品推荐

