IanDess IanDess - 1 month ago 7
Ajax Question

Javascript XMLHttpRequest with formdata sending empty body

I tried sending files like this

var formData = new FormData();
formData.append("avatar", document.getElementById('imageFile').files[0]);

var request = new XMLHttpRequest;
request.open("PATCH", "http://localhost:9090/users/me/avatar");
request.send(formData);


However, no matter what i try the actual content of the selected file that should be sent remains blank. Here's a screenshot of Chrome's network tab

Avatar field is empty

I tried with different files and different request methods and it's always the same.

I also tried
formData.append("testfield", "some string");
and that is sent correctly, i can see the "some string" in request body, the issue appears to be with files.

Am i doing something wrong?

Thanks

Answer

PATCH is a method intended for API changes, not sending files.
You should use POST or PUT to upload a file

var formData = new FormData();
formData.append("avatar", document.getElementById('imageFile').files[0]);

var request = new XMLHttpRequest;
request.open("POST", "http://localhost:9090/users/me/avatar");
request.send(formData);

Also, you won't be able to see the data when logging a formData object to the console.