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

如何在React中读取文件夹内文件名以实现PDF下载

解决React中读取静态PDF文件名实现下载的问题

情况1:基于Create React App(CRA)的项目

如果PDF文件存放在src/pdf/目录下,可以通过require.context批量读取目录内的PDF文件名及路径:

// 批量读取src/pdf下的所有PDF文件
const pdfContext = require.context('./pdf', false, /\.pdf$/);
const pdfFiles = pdfContext.keys().map(key => ({
  fileName: key.replace('./', ''),
  fileUrl: pdfContext(key)
}));

// 渲染下载按钮组
return (
  <div>
    {pdfFiles.map((pdf, idx) => (
      <button key={idx} style={{ marginRight: '8px' }}>
        <a 
          href={pdf.fileUrl} 
          download={pdf.fileName}
          target="_blank" 
          rel="noopener noreferrer"
        >
          下载 {pdf.fileName}
        </a>
      </button>
    ))}
  </div>
);

如果PDF文件放在public/pdf/目录(CRA会原封不动打包该目录下的文件),require.context无法直接读取,此时可以:

  • 提前维护文件名列表,直接使用/pdf/xxx.pdf作为链接地址;
  • 若需动态读取,只能依赖后端接口返回文件名列表(浏览器端无法直接访问本地文件系统)。

情况2:基于Vite的项目

Vite原生支持import.meta.glob批量导入静态资源,实现更简洁:

// 批量读取src/pdf下的所有PDF文件,{ eager: true }表示立即加载
const pdfModules = import.meta.glob('./pdf/*.pdf', { eager: true, as: 'url' });
const pdfFiles = Object.entries(pdfModules).map(([filePath, fileUrl]) => ({
  fileName: filePath.split('/').pop() || '未知文件.pdf',
  fileUrl: fileUrl as string
}));

// 渲染下载按钮组
return (
  <div>
    {pdfFiles.map((pdf, idx) => (
      <button key={idx} style={{ marginRight: '8px' }}>
        <a 
          href={pdf.fileUrl} 
          download={pdf.fileName}
          target="_blank" 
          rel="noopener noreferrer"
        >
          下载 {pdf.fileName}
        </a>
      </button>
    ))}
  </div>
);

关键注意点

  • 如果是运行时动态添加到项目文件夹的PDF(比如用户上传的文件),前端浏览器无法直接读取本地文件系统的文件名,必须依赖后端服务:将文件上传至后端存储,后端返回文件名和下载链接,前端再渲染对应按钮。
  • download属性可以指定下载后的文件名,避免浏览器自动生成随机文件名,提升用户体验。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 19:12:21