Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XMLHttpRequest multipart/form-data: Invalid boundary in multipart

I am sending post data via XMLHttpRequest:

var xmlHttp=new XMLHttpRequest();
xmlHttp.open("POST", domain, true);
xmlHttp.setRequestHeader("Content-type","multipart/form-data");
var formData = new FormData();  
formData.append("data", data_json_string);
xmlHttp.send(formData);

In Python, I get an error if I try to get the POST (or FILES or anything) data:

MultiPartParserError: Invalid boundary in multipart: None

Can this never work?? Do I really need to create the form body as a single string where I loop through the parameters and place a boundary string before and after each one? And, if so, what should that look like? How do I get it from my POST in Python?? Or is there an easier way. I'm looking around and not finding much on this.

btw, I am using "multipart/form-data" because my string data is really long and this is a faster way to send it. It has worked for me when I create a form and post it, targeting it to an iframe. But here I much prefer xmlHttp.

like image 812
user984003 Avatar asked Sep 03 '13 11:09

user984003


1 Answers

Do not set the Content-Type header yourself. It will be properly set when .send()ing the data, including the proper generated boundary, which your manually generated header lacks.

The spec clearly states that .send(FormData) will use multipart/form-data encoding.

If data is a FormData

Let the request entity body be the result of running the multipart/form-data encoding algorithm with data as form data set and with UTF-8 as the explicit character encoding.

Let mime type be the concatenation of "multipart/form-data;", a U+0020 SPACE character, "boundary=", and the multipart/form-data boundary string generated by the multipart/form-data encoding algorithm.

like image 139
nmaier Avatar answered Oct 18 '22 11:10

nmaier