javascript xhr file upload without jQuery

允我心安 提交于 2019-12-05 04:01:22

问题


i have some trouble to make xhr file upload without jquery. (please don't said that use jQuery).

if the browser support FormData API and use it, i heard it is possible to upload file(s) also.

the matter is i don't know how the attach file into FormData object. and second problem is how to send the FormData via XHR? i mean, look at the code below:

var formData = new FormData();
formData.append('somevalue', 'somevalue'); // string
formData.append( ???, ??? ); // file

var xhr = new XMLHttpRequest();
xhr.setRequestHeader('Content-type', 'multipart/form-data; charset=UTF-8');

xhr.open('post', 'URL TO UPLOAD', true);
xhr.onreadystatechange = function() { ... };

xhr.send( ?? WHAT SHOULD BE HERE IF THE FORM DATA CONTAINS FILE? JUST FORM DATA ?? );

please look at the code, especially second "formData.append part". i don't know how to append FILE DATA into formData object.

and second, if i want to send "formData" via XHR, do i just put "formData" variable into "xhr.send" method like this?

xhr.send(formData);

or, should i do something more? it is hard to find the information on google so if someone know about this problem, it will be very appreciated to tell me or advice me how should i do next. thanks!


回答1:


formData.append( ???, ??? ); // file

Yes, a file. There is an example in the MDN documentation:

formData.append('userpic', myFileInput.files[0], 'chris.jpg');
xhr.setRequestHeader('Content-type', 'multipart/form-data; charset=UTF-8');

Remove that. XHR will generate the correct content type for you. Doing it manually will fail to include the (essential) boundary information.

and second, if i want to send "formData" via XHR, do i just put "formData" variable into "xhr.send" method like this?

Yes.



来源:https://stackoverflow.com/questions/36475737/javascript-xhr-file-upload-without-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!