Today I tried to get my head around a problem where a file upload using AJAX didn’t work. That’s when I encountered the FormData object. A FormData object consists of key/value pairs that can be sent using a XMLHttpRequest.

If we want to send files asynchronously, the first thing we need is a <input>-element to hold the file.

<input type="file" name="myfile" id="myupload">

In JavaScript, to prepare the data to be sent, we have to create a new FormData object and append the file the user entered.

var fileInput = document.getElementById("myupload"),
    uploadFile = fileInput.files;

var data = new FormData();
data.append("uploadfile", uploadFile);

We then can use the newly created FormData object and send it using XMLHttpRequest:

var request = new XMLHttpRequest();
request.open("POST", "http://mydomain.com/submit.php");
request.send(data);

If we are using PHP on the server side of things, we can then access the sent file using the $_FILES array.

There’s one thing to consider though: browser support for FormData starts at IE 10. But a fallback solution should be easy to provide as we can just sent the form using a regular HTTP request.

And that’s what I learnt today.