Search code examples
javascriptajaxfile-uploadxmlhttprequestform-data

javascript xhr file upload without jQuery


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!


Solution

  • 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.