FormData.append()不适用于文件 [英] FormData.append() doesn't work with files

查看:140
本文介绍了FormData.append()不适用于文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试在JavaScript中将 File 对象附加到 FormData 对象,但是它不起作用,仅添加了一个空对象.如果我尝试附加键/值,则可以正常工作.

I try to append a File object to a FormData object in JavaScript, but it doesn't work and only a empty object is added. If I try to append a key/value it works fine.

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

There is no error / warning message in the console. I activated all channels.

我从网络和MDN尝试了一些示例.但是没有任何帮助.我不明白为什么?是否出于安全原因阻止了文件访问?

I try out examples from the web and from the MDN. But nothing helps. I don't understand why? Is file access blocked by security reasons?

我正在使用Firefox 64.0或Chrome 71.0.当前,该示例不包含任何客户端-服务器通信.但是我以两种方式进行了尝试:作为本地文件和从Web服务器加载的页面.

I'm use Firefox 64.0 or Chrome 71.0. Currently the example doesn't contain any client-server communication. But I tried it in two ways: as a local file and a page loaded from a web server.

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

The background of my question is, I would like to upload files with XmlHttpRequest in a script to a server.

控制台

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

CachingFoX

推荐答案

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

Your FormData has the file but it not shown because JSON.stringify will log the file as an empty obj.

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

Please use this to log all your form data

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

这篇关于FormData.append()不适用于文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆