Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using XMLHttpRequest send file with data

I'm trying to ajaxlly upload a file including i want to add a post data with it

var xhr = this._xhrs[id] = new XMLHttpRequest();
var queryString = qq.obj2url(params, this._options.action);
        xhr.open("POST", queryString, true);
        xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
        xhr.setRequestHeader("X-File-Name", encodeURIComponent(name));
        xhr.setRequestHeader("Content-Type", "application/octet-stream");
        xhr.send(file);

how can i add x=y as a post data ?

like image 368
Hilmi Avatar asked May 14 '12 12:05

Hilmi


2 Answers

var file = $("#file_input")[0].files[0];
//for pure javascript use
var file = document.querySelector('input[type=file]')[0].files[0];

var formData = new FormData();
formData.append("myfile", file);
formData.append("text_unput", "Hello");

var xhr = new XMLHttpRequest();
xhr.open('POST', '/url', true);
xhr.send(formData);
like image 53
Habibutsu Avatar answered Sep 20 '22 12:09

Habibutsu


CORRECT NEW ANSWER

Look at the @habibutsu's answer below

WRONG OLD ANSWER

You can't post a file and a form data as x=y&w=z. They are two different Content Types.

For x=y you should use a content-type like this: application/x-www-form-urlencoded

I suggest you to split your AJAX request in two different or insert these data into the url: myUrl + 'query.php?x=y'.

Ciao

Wilk

like image 26
Wilk Avatar answered Sep 21 '22 12:09

Wilk