简体   繁体   English

Javascript XMLHttpRequest与formdata发送空主体

[英]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 这是Chrome的“网络”标签的屏幕截图

阿凡达字段为空

I tried with different files and different request methods and it's always the same. 我尝试使用不同的文件和不同的请求方法,并且始终相同。

I also tried formData.append("testfield", "some string"); 我也尝试了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. PATCH是用于API更改而不发送文件的方法。
You should use POST or PUT to upload a file 您应该使用POST或PUT上传文件

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. 另外,将formData对象记录到控制台时,您将看不到数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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