問題描述
如何創(chuàng)建一個 HTTP 請求,該請求使用 PHP 服務(wù)器可以接收的 JavaScript 發(fā)送一個文件和一些 post 數(shù)據(jù)?
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);
為了讓這個工作,我需要一個包含輸入類型文件字段的文件"變量,但是在哪里放置額外的帖子數(shù)據(jù)?我也想發(fā)送描述文本.假設(shè)我還需要使用 xhr.send 來發(fā)送請求...
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 數(shù)據(jù)應(yīng)該作為另一個 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--
這里發(fā)送了兩個變量:要上傳的文件和一個名稱 = "submit-name" 且值為 Larry
的輸入.您可以擁有與想要發(fā)布的變量一樣多的 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 框架,則可以簡化大部分管道.這是一個 優(yōu)秀插件 應(yīng)該 完成工作.
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.
這篇關(guān)于如何使用包含文件和發(fā)布數(shù)據(jù)的 JavaScript 創(chuàng)建 AJAX 請求的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!