You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用readAsText()读取文件返回路径而非内容的技术问题求助

问题分析与解决方案

你的代码根本没读取本地文件内容——你只是把文件路径字符串塞进了Blob和File对象里,所以FileReader自然只会输出路径文本,而不是文件里的内容。

浏览器出于安全限制,不允许脚本直接通过本地路径读取文件,必须通过用户主动选择文件的方式来获取文件对象。下面是两种场景的正确实现:

浏览器网页场景(合规方案)

  1. 先添加HTML文件选择控件和内容展示区域:
<input type="file" id="fileInput" accept=".txt">
<div id="contentDisplay"></div>
  1. 对应的JavaScript代码:
const fileInput = document.getElementById('fileInput');
const contentDisplay = document.getElementById('contentDisplay');

fileInput.addEventListener('change', function(e) {
  const selectedFile = e.target.files[0];
  if (!selectedFile) return;

  const reader = new FileReader();
  reader.onload = function() {
    // 把文件内容显示到div里
    contentDisplay.textContent = reader.result;
    console.log(reader.result);
  };

  reader.onerror = function() {
    console.error('文件读取失败:', reader.error);
  };

  reader.readAsText(selectedFile);
});

用户点击文件选择框选中目标txt文件后,脚本就会读取内容并显示到指定div中。

桌面应用场景(比如Electron)

如果是基于Node.js的桌面应用,可以直接用文件系统模块读取本地文件:

const fs = require('fs').promises;
const filePath = 'c:\\Users\\Demostenes\\Desktop\\sub.txt';

async function loadFileContent() {
  try {
    const content = await fs.readFile(filePath, 'utf8');
    console.log(content);
    // 渲染进程中更新div内容
    document.getElementById('contentDisplay').textContent = content;
  } catch (err) {
    console.error('读取文件出错:', err);
  }
}

loadFileContent();

内容的提问来源于stack exchange,提问作者Salvatore Improta

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 13:12:44