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

重新创建input元素仍出现net::ERR_UPLOAD_FILE_CHANGED错误的原因

问题原因及解决方案

你遇到的Chrome文件上传报错问题,核心有两个原因:

1. 代码错误导致input重置失效

你的代码存在两处低级错误,直接导致文件输入框无法被正确重置,浏览器始终持有旧的文件引用:

  • getElemenetById拼写错误,正确写法是getElementById(少了一个t)
  • resetFileInput函数中,定义了newInput变量,但后续赋值用的是未定义的input,应该替换为newInput

这些错误会让旧的input元素残留,浏览器无法获取新的文件快照,修改文件后自然触发错误。

2. Chrome的安全机制限制

即便修正了代码,当用户选择文件后修改它,再次选择同一文件时,Chrome会触发文件变更检测——这是浏览器的安全防护机制,防止恶意程序在用户不知情的情况下修改本地文件并上传。浏览器会对比文件的元数据(修改时间、哈希值),如果和之前选中的文件快照不一致,就会抛出错误。


修正后的代码

先修复代码错误,确保input能被正确重置,让浏览器可以获取最新的文件引用:

<div id="input_file_container">
  <input type="file" id="file" />
</div>

<script>
function uploadFile() {
  let formData = new FormData();
  // 修正拼写错误
  const file = document.getElementById("file").files[0];
  if (!file) return; // 增加判断,避免无文件时触发上传
  formData.append("file", file);

  fetch("/upload", {
      method: "POST",
      body: formData
    })
    .then(response => {
      // 处理响应逻辑
    })
    .catch(function(error) {
      console.log(error);
    })
    .finally(function() {
      resetFileInput();
    })
}

function resetFileInput() {
  // 修正拼写错误
  const oldInput = document.getElementById("file");
  oldInput.remove();
  const newInput = document.createElement("input");
  // 修正变量名错误
  newInput.type = "file";
  newInput.id = "file";
  document.getElementById("input_file_container").append(newInput);
}
</script>

额外优化方案

如果仍遇到文件变更错误,可以通过读取文件内容的方式,强制获取最新数据(适合小文件场景):

// 替换原formData.append逻辑
const reader = new FileReader();
reader.onload = function(e) {
  const blob = new Blob([e.target.result], { type: file.type });
  formData.append("file", blob, file.name);
  // 在此处执行fetch上传逻辑
};
reader.readAsArrayBuffer(file);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 20:40:10