0

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

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

7 Comments

Thanks, but it's the same, i tried with POST and PUT already and it was the same. Tried it again just now, no difference. This is driving me crazy, seems really weird.
And if you log document.getElementById('imageFile').files[0] what do you get? How are you catching the files on the serverside?
I'm getting the file i selected logged in console so that's working. Server side at this point doesn't matter because the field "avatar" is sent with no contents, see image above :(
That's what the request should look like, you won't see the binary data in a POST or PUT request in the console, you still have to catch that file on the server.
Oh my god i'm stupid. I expected to see something there in the network tab. Turned out that it was an error with my server code, but a really weird one, so i suspected that something was wrong with my client code.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.