Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set boundary while using XmlHttpRequest and FormData

I am trying to set the boundary correctly in the header while using FormData to post the XmlHttpRequest:

xhr.open("POST",url);
xhr.setRequestHeader("Content-type","multipart/form-data; boundary=...");

var formData = new FormData();
formData.append("filename", inputId.files[0]);
formData.append(...);

xhr.send(formData);

How do I get the boundary to be set in the request header here. I saw the request being set, the boundary is somehow created in the request. But the server has no idea on how to interpret it.

like image 353
Ankit Avatar asked Jul 11 '12 22:07

Ankit


People also ask

What is Formdata boundary?

multipart/form-data contains boundary to separate name/value pairs. The boundary acts like a marker of each chunk of name/value pairs passed when a form gets submitted.

What is boundary parameter?

The boundary parameter is a text string used to delineate one part of the message body from another. All boundaries start with two hyphens (--). The final boundary also concludes with two hyphens (--). The boundary can be made up of any ASCII character except for a space, a control character, or special characters.


1 Answers

ES method

Simply don't set the Content-Type header manually and the browser will automatically set "multipart/form-data; boundary=..." value.


jQuery method

If you're using jQuery, set contentType option to false:

$.ajax({
    url: url,
    type: 'POST',
    data: formData,
    processData: false,
    contentType: false
});
like image 143
Anton Morozov Avatar answered Oct 31 '22 07:10

Anton Morozov