Search code examples
javascriptajaxfileform-data

FormData.append() doesn't work with files


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.

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?

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.

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

Console

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

<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

<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>

Thank you for your help

CachingFoX


Solution

  • 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]); 
    }