views:

75

answers:

3

How can I create a HTTP request that sends one file and some post data with JavaScript that can be received by a PHP server?

I have found the following suggestion but it does not seem to be complete

xhr.open("POST", "upload.php");
var boundary = '---------------------------';
boundary += Math.floor(Math.random()*32768);
boundary += Math.floor(Math.random()*32768);
boundary += Math.floor(Math.random()*32768);
xhr.setRequestHeader("Content-Type", 'multipart/form-data; boundary=' + boundary);
var body = '';
body += 'Content-Type: multipart/form-data; boundary=' + boundary;
//body += '\r\nContent-length: '+body.length;
body += '\r\n\r\n--' + boundary + '\r\n' + 'Content-Disposition: form-data; name="';
body += 'myfile"; filename="'+file.fileName+'" \r\n';
body += "Content-Type: "+file.type;
body += '\r\n\r\n';
body += file.getAsBinary();
body += '\r\n'
body += '--' + boundary + '\r\n' + 'Content-Disposition: form-data; name="submitBtn"\r\n\r\nUpload\r\n';
body += '--' + boundary + '--';
xhr.setRequestHeader('Content-length', body.length);

To get this working I need to have a 'file' variable that contains an input type file field but where to put additional post data? I want to send a description text as well. suppose I would also need to use xhr.send to send the request...

A: 

Why not use jquery? It save you setting up your own XHR request.

Rob
I would like to know how to create a correct HTTP request with JavaScript.
Tirithen
http://www.doxdesk.com/img/updates/20091116-so-large.gif
troelskn
+1  A: 

Additional POST data should be placed as another Content-Disposition. Example:

Content-Type: multipart/form-data; boundary=AaB03x

--AaB03x
Content-Disposition: form-data; name="submit-name"

Larry
--AaB03x
Content-Disposition: form-data; name="files"; filename="file1.txt"
Content-Type: text/plain

... contents of file1.txt ...
--AaB03x--

Here two variables are sent: the file to be uploaded and a input with name = "submit-name" and value Larry. You could have as many Content-Dispositions as variables you would like to POST.

Of course much of the plumbing could be simplified if you used a js framework like jQuery. Here's an excellent plugin which should do the job.

Darin Dimitrov
Thanks for the tip, I'll try that.
Tirithen
A: 

AFAIK It's not possible to send files with XmlHttpRequest.

ZippyV