6

我正在尝试 ajaxlly 上传一个文件,包括我想用它添加一个帖子数据

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);

如何添加x=y为帖子数据?

4

2 回答 2

8
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);
于 2015-08-17T15:25:01.510 回答
1

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

于 2012-05-14T12:37:36.830 回答