Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript XHR send multipart/form-data

I'm trying to send a multipart/form-data content-type request:

var xhr = new XMLHttpRequest();

xhr.onreadystatechange = function(){
    if(xhr.readyState==4){
         alert(xhr.responseText);
    }
}

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

xhr.send('-----------------------------275932272513031 Content-Disposition: form-data; name="name"

test

----------------------------275932272513031--');

Then in php I just print the $_POST array

print_r($_POST);

But I get an empty array each time. I expect to see

Array (
    name => "test"
)

What am I doing wrong?

like image 459
php_nub_qq Avatar asked Dec 22 '13 14:12

php_nub_qq


People also ask

How do I set the multipart form data in XMLHttpRequest?

you can upload it as below: var formData = new FormData(); formData. append("myFile", document.

How do you send a file using multipart form data?

Multipart form data: The ENCTYPE attribute of <form> tag specifies the method of encoding for the form data. It is one of the two ways of encoding the HTML form. It is specifically used when file uploading is required in HTML form. It sends the form data to server in multiple parts because of large size of file.

What is Enctype multipart form data?

enctype property is the MIME type of content that is used to submit the form to the server. Possible values are: application/x-www-form-urlencoded : The initial default type. multipart/form-data : The type that allows file <input> element(s) to upload file data.


1 Answers

Your code failed because you've used "Enter" instead of an escaped line break character (\n).
JavaScript doesn't support "first line[Enter]second line". If you need a string with a line break, use "first line\nsecond line".

Once you've fixed this problem, your code should work as intended (with one caveat, see final note):

var xhr = new XMLHttpRequest();
xhr.onload = function() {
     alert(xhr.responseText);
};
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type","multipart/form-data; boundary=---------------------------275932272513031");
xhr.send('-----------------------------275932272513031\n' +
         'Content-Disposition: form-data; name="name"\n\n' +
         'test\n\n' +
         '----------------------------275932272513031--');

NOTE: Your code will only work for payloads that consists of UTF-8 characters, not binary data. If you want to learn more about submitting forms with binary data via XMLHttpRequest, see this answer and its linked references.

like image 64
Rob W Avatar answered Oct 19 '22 04:10

Rob W