简体   繁体   中英

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

阿凡达字段为空

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM