如何创建一个AJAX请求的Jav​​aScript,它包含两个文件,​​并发布数据创建一个、两个、文件、数据

2023-09-10 13:35:06 作者:30.乱心弃情

我怎样才能创建一个发送一个文件和一些后数据用JavaScript可以由PHP服务器接收HTTP请求?

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

要得到这个工作,我需要有一个包含一个输入类型的文件领域,但在哪里把额外的后数据的'文件'变量?我想送一个说明文字也是如此。想我还需要使用xhr.send发送的请求......

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

推荐答案

附加POST数据应该放在作为另一个内容处置。例如:

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.

当然,大部分管道的,如果你使用JS框架像jQuery可以简化。下面是href="http://jquery.malsup.com/form/" rel="nofollow">优秀的插件应的