文件选择完成后奇怪的文件名回调

strange filename callback after file selection finish

我有这段代码,它会在文件 selected 后显示文件名:

<input id="file-input" type="file" />
<script>
  const fileInput = document.querySelector('#file-input');
  fileInput.onchange = function(){
    console.log('file name:', this.value)
  }
</script>

我准备了两个windows快捷方式文件(Desktop制作--->右键--->新建--->快捷方式)

  1. 第一个快捷方式文件

目标是https://www.baidu.com/ and the file name is www.baidu.com

在我select这个文件之后,回调中的输出是C:\fakepath\www.baidu.com.url,这是预期的

  1. 第二个快捷方式文件

目标是 https://www.google.com/ and the file name is www.google.com

但在 select 这个文件之后,我希望它在回调中输出 C:\fakepath\www.google.com.url ,但它输出类似 C:\fakepath\TQCJEVEM

为什么会这样?

免责声明:我仍然不确定为什么,但我可以猜测是什么 正在发生。

当您创建目标为网络资源的 windows 快捷方式(如上文所述)时,它会创建一个具有 .url 扩展名的 URL file
注意: Microsoft Windows 不显示“.url”文件扩展名,即使它存在于文件名中。因此,使用 Windows 网络浏览器保存的 URL 文件将仅显示文件名前缀。

windows 上的一个 URL 文件看起来像这样:

[{000214A0-0000-0000-C000-000000000046}]
Prop3=19,11
[InternetShortcut]
IDList=
URL=https://www.baidu.com/
HotKey=0

当您上传百度快捷方式时,windows只是上传包含上述内容的文件。

然而
当您上传 google 快捷方式时 ,windows 实际上会下载 www.google.com 网站登录页面的副本,将其存储在本地缓存中某处..\AppData\Local\Microsoft\Windows\INetCache\.. 文件夹,然后上传该缓存文件,该文件的文件名可以是随机生成的字符串。每次新尝试都会为文件名生成一个新字符串。

希望这能为您指明正确的方向。

编辑: 要验证上传文件的内容,请使用 this answer.

中的示例代码稍微修改您的代码

function init() {
  document.getElementById('fileInput').addEventListener('change', handleFileSelect, false);
}

function handleFileSelect(event) {
  const reader = new FileReader()
  reader.onload = handleFileLoad;
  reader.readAsText(event.target.files[0])
}

function handleFileLoad(event) {
  console.log(event);
  document.getElementById('fileContent').textContent = event.target.result;
}
<!DOCTYPE html>
<html>

<head>
  <script src="script.js"></script>
</head>

<body onload="init()">
  <input id="fileInput" type="file" name="file" />
  <pre id="fileContent"></pre>
</body>

</html>