如何使用包含文件和发布数据的 JavaScript 创建 AJAX 请求

如何创建一个 HTTP 请求,该请求使用 PHP 服务器可以接收的 JavaScript 发送一个文件和一些 post 数据?

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 += '
Content-length: '+body.length;
body += '

--' + boundary + '
' + 'Content-Disposition: form-data; name="';
body += 'myfile"; filename="'+file.fileName+'" 
';
body += "Content-Type: "+file.type;
body += '

';
body += file.getAsBinary();
body += '
'
body += '--' + boundary + '
' + 'Content-Disposition: form-data; name="submitBtn"

Upload
';
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 数据应该作为另一个 Content-Disposition 放置.示例:

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

这里发送了两个变量:要上传的文件和一个名称 = "submit-name" 且值为 Larry 的输入.您可以拥有与想要发布的变量一样多的 Content-Disposition.

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.

当然,如果您使用像 jQuery 这样的 js 框架,则可以简化大部分管道.这是一个 优秀插件 应该 完成工作.

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.

相关文章