Search code examples
javascriptxmlhttprequest

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 ?


Solution

  • 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