How to create an AJAX request with JavaScript that

2020-03-05 03:09发布

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...

3条回答
2楼-- · 2020-03-05 03:12

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

查看更多
Bombasti
3楼-- · 2020-03-05 03:16

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

查看更多
霸刀☆藐视天下
4楼-- · 2020-03-05 03:31

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.

查看更多
登录 后发表回答