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

ReactJS项目如何访问局域网文件?多种尝试均失败求方案

React项目访问局域网共享文件解决方案

核心原因:React本地开发服务运行在HTTP环境,浏览器出于安全限制,不允许直接从HTTP页面访问SMB协议(\\192.XXX.X.XXX\...)的局域网共享文件,这是所有尝试失败的根本问题。以下是可行的解决思路:

一、搭建本地代理服务(推荐)

通过Node.js代理服务,将SMB共享文件转换为HTTP可访问的资源,绕开浏览器的安全限制。

1. 编写代理服务代码

创建一个新文件夹,新建proxy-server.js文件:

const express = require('express');
const SMB2 = require('smb2');
const app = express();
const port = 5000;

// 配置SMB连接信息
const smbClient = new SMB2({
  share: '\\\\192.XXX.X.XXX\\Thanigahai', // 共享文件夹路径,注意转义反斜杠
  username: '你的共享用户名', // 无密码可省略
  password: '你的共享密码' // 无密码可省略
});

// 提供文件访问接口
app.get('/files/demo.docx', (req, res) => {
  smbClient.readFile('demo.docx', (err, fileData) => {
    if (err) {
      console.error('读取文件失败:', err);
      return res.status(500).send('文件读取失败');
    }
    // 设置正确的文件类型头
    res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document');
    res.send(fileData);
  });
});

app.listen(port, () => {
  console.log(`代理服务已启动: http://localhost:${port}`);
});

2. 安装依赖并启动服务

在该文件夹下执行命令:

npm init -y
npm install express smb2
node proxy-server.js

3. React项目中访问文件

方式1:使用@cyntler/react-doc-viewer预览

import { DocViewer } from "@cyntler/react-doc-viewer";
import { useEffect, useState } from "react";

export default function LocalFileViewer() {
  const [fileUrl, setFileUrl] = useState(null);

  useEffect(() => {
    // 从代理服务获取文件Blob,生成临时URL
    fetch('http://localhost:5000/files/demo.docx')
      .then(res => res.blob())
      .then(blob => {
        const tempUrl = URL.createObjectURL(blob);
        setFileUrl(tempUrl);
      })
      .catch(err => console.error('获取文件出错:', err));
  }, []);

  return (
    <div style={{ width: '80%', margin: '0 auto' }}>
      {fileUrl ? (
        <DocViewer documents={[{ uri: fileUrl }]} />
      ) : (
        <p>加载文件中...</p>
      )}
    </div>
  );
}

方式2:提供下载链接

<a href="http://localhost:5000/files/demo.docx" download="demo.docx">
  下载局域网文件
</a>

二、为什么之前的方法失败

  • Craco路径解析失败:Webpack(Craco基于Webpack)仅支持解析本地文件系统或HTTP路径,SMB协议路径不在其解析范围内。
  • 谷歌/微软预览链接:这类服务要求文件是公网可访问的HTTP/HTTPS资源,无法直接读取局域网SMB共享文件,因此报错。
  • @cyntler/react-doc-viewer报错:直接传入SMB路径时,浏览器会将其视为本地文件路径,但React项目运行在开发服务器上,该路径不存在,导致404错误。

内容的提问来源于stack exchange,提问作者Thanigahai Vel

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 13:42:39