FormData.append() 不适用于文件

FormData.append() doesn't work with files

我尝试将 File 对象附加到 JavaScript 中的 FormData 对象,但它不起作用,只添加了一个空对象。如果我尝试附加一个 key/value 它工作正常。

控制台中没有错误/警告消息。我激活了所有频道。

我尝试了来自网络和 MDN 的示例。但没有任何帮助。我不明白为什么?文件访问是否因安全原因被阻止?

我使用的是 Firefox 64.0 或 Chrome 71.0。目前该示例不包含任何客户端-服务器通信。但我尝试了两种方式:本地文件和从网络服务器加载的页面。

我的问题背景是,我想在脚本中使用 XmlHttpRequest 将文件上传到服务器。

控制台

File(234321) {name: "refresh2.gpx", lastModified: 1503041677210,
              lastModifiedDate: Fri Aug 18 2017 09:34:37 GMT+0200 (...),
              webkitRelativePath: "", size: 234321, …}

{"key":"value","userfile":{}}

HTML正文

<body>
<form id="file-form" action="handler.php" method="POST">
  <input type="file" id="file-select" />
  <button type="submit" id="upload-button">Upload</button>
</form>
</body>

脚本

<script>
document.getElementById('file-form').onsubmit = function(event) {
    event.preventDefault();

    // Get the selected files from the input.
    var files = document.getElementById('file-select').files;

    // Create a new FormData object.
    var formData = new FormData();
    console.log(files[0]);
    formData.append("key", "value");
    formData.append("userfile", files[0]);

    // dump formData object
    var object = {};
    formData.forEach(function(value, key){
        object[key] = value;
    });
    var json = JSON.stringify(object);
    console.log(json);

    // xmlhttprequest part comes here....
}
</script>
</html>

感谢您的帮助

CachingFoX

您的 FormData 有文件但未显示,因为 JSON.stringify 会将文件记录为空对象。

请使用它来记录您所有的表单数据

for (var pair of formData.entries()) {
    console.log(pair[0]+ ', ' + pair[1]); 
}