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

如何在浏览器中通过JavaScript获取上传文件的本地目录路径?

关于input[type="file"]获取本地真实文件路径的问题

直接获取用户文件的完整本地系统路径(如C:\Users\Windows 10\Downloads\Video\file.name)完全不可能——现代浏览器出于隐私和安全保护,会刻意隐藏真实路径,仅返回文件名或伪路径(比如C:\fakepath\filename.ext),这是浏览器的固有安全机制,无法绕过。

可行的替代方案

  • 仅显示文件名:通过File对象的name属性获取文件名,这是最常用的场景:
<input id="file" type="file" onchange="displayFileName()" />
<div id="selectedFile"></div>

<script>
function displayFileName() {
  const input = document.getElementById('file');
  if (input.files.length > 0) {
    document.getElementById('selectedFile').textContent = `选中文件:${input.files[0].name}`;
  }
}
</script>
  • 处理文件内容/上传:无需真实路径,直接通过File对象即可完成文件读取、上传等操作:
<input id="file" type="file" onchange="handleFile()" />
<pre id="filePreview"></pre>

<script>
function handleFile() {
  const file = document.getElementById('file').files[0];
  if (!file) return;

  const reader = new FileReader();
  reader.onload = (e) => {
    document.getElementById('filePreview').textContent = e.target.result;
  };
  // 这里以读取文本为例,也可使用readAsDataURL处理图片等
  reader.readAsText(file);
}
</script>
  • 桌面应用场景:如果是基于Electron等框架开发的桌面应用(而非普通网页),可借助Node.js的文件系统API获取真实路径,但这仅适用于拥有系统权限的桌面环境,普通网页无法实现。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 23:50:30