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

如何用HTML/JavaScript让FileReader读取网站服务器文件?

读取服务器端本地文件的JavaScript解决方案

问题背景

已掌握通过HTML input 控件读取用户上传文件的方法,现有代码可正常读取用户上传的文本文件。现在需要修改代码,读取服务器上路径为 Website_Data/Recipes/Ultimate_Cookies.recp 的文件,而非用户上传的文件。尝试使用File类创建对象并通过FileReader读取,但无效果。

原工作代码:

TestFileIO.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Read Text File</title>
</head>
<body>
    <h1 id="textToChange">Hello World!</h1>

    <input type="file" id="upload">

    <br>

    <p id="outputBx"></p>

    <script src="/JS_Scripts/testFileIOAgain.js"></script>
</body>
</html>

TestFileIO.js

console.log('this is testFileIO.js');

let upload = document.getElementById('upload');
let outputBx = document.getElementById('outputBx');

upload.addEventListener('change', ()=> {
    let fr = new FileReader();
    fr.readAsText(upload.files[0]);

    fr.onload = function()
    {
        outputBx.innerHTML = fr.result;
    };
});

尝试的无效代码:

console.log('this is testFileIO.js');

let upload = document.getElementById('upload');
let outputBx = document.getElementById('outputBx');

upload.addEventListener('change', ()=> {
    let fr = new FileReader();

    fileToRead = new File([""], "Website_Data/Recipes/Ultimate_Cookies.recp", []);
    fr.readAsText(fileToRead);
    
    outputBx.innerHTML = fr.result;
});

错误原因分析

  1. File类的误用:File对象仅用于表示用户本地设备中选择的文件,无法通过传入服务器文件路径来创建指向服务器文件的实例,上述代码创建的只是一个空内容的文件对象,根本没有关联到服务器上的目标文件。
  2. 异步操作顺序错误:即使File对象有效,readAsText是异步操作,直接在调用后就赋值outputBx.innerHTML = fr.result,此时读取操作尚未完成,fr.result还未获取到内容。

正确实现方案

要读取服务器上的静态文件,需要通过HTTP请求获取文件内容,推荐使用现代的fetch API,也可以用传统的XMLHttpRequest。以下是两种实现方式:

方式1:使用Fetch API(推荐)

修改TestFileIO.js如下:

console.log('this is testFileIO.js');

let upload = document.getElementById('upload');
let outputBx = document.getElementById('outputBx');

upload.addEventListener('change', async ()=> {
    try {
        // 发起HTTP请求获取服务器文件
        const response = await fetch('Website_Data/Recipes/Ultimate_Cookies.recp');
        if (!response.ok) {
            throw new Error(`请求失败:${response.status}`);
        }
        // 读取文本内容
        const fileContent = await response.text();
        // 将内容显示到页面
        outputBx.innerHTML = fileContent;
    } catch (error) {
        outputBx.innerHTML = `读取文件失败:${error.message}`;
        console.error(error);
    }
});

方式2:使用XMLHttpRequest(兼容旧浏览器)

修改TestFileIO.js如下:

console.log('this is testFileIO.js');

let upload = document.getElementById('upload');
let outputBx = document.getElementById('outputBx');

upload.addEventListener('change', ()=> {
    const xhr = new XMLHttpRequest();
    xhr.open('GET', 'Website_Data/Recipes/Ultimate_Cookies.recp', true);
    
    xhr.onload = function() {
        if (xhr.status >= 200 && xhr.status < 300) {
            // 请求成功,获取文件内容
            outputBx.innerHTML = xhr.responseText;
        } else {
            outputBx.innerHTML = `读取文件失败:状态码 ${xhr.status}`;
        }
    };
    
    xhr.onerror = function() {
        outputBx.innerHTML = '网络错误,无法读取文件';
        console.error('请求出错');
    };
    
    // 发送请求
    xhr.send();
});

注意事项

  • 确保服务器上的Website_Data/Recipes/Ultimate_Cookies.recp文件路径正确,路径是相对于当前HTML页面的位置(若HTML在根目录,则路径为相对根目录的路径)。
  • 若服务器有跨域限制或文件权限设置,需确保前端请求能正常访问该文件。
  • 若不需要用户触发(比如页面加载时自动读取),可把请求代码放在DOMContentLoaded事件中,而非input的change事件里。

内容的提问来源于stack exchange,提问作者Zachary Lund

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 21:12:07