一个老外写的基于ajax的文本上传代码
当然,仅仅是文本文件,而且是事先知道内容。
对于以下问题,千万不要想歪了啊.
1。能否上传客户端任意文件 比如 c:\windows\help.htm
2。能否上传二进制文件 比如: regedit.exe
原文来自google论坛 javascript版
http://groups.google.com/group/comp.lang.javascript/browse_thread/thread/cc7cf728bec973bd/312d118bcd6c780a?q=ajax+prototype&rnum=1#312d118bcd6c780a
NextOne wrote:
> Is it possible to send an AJAX XMLHttpRequest using prototype.js API
> for a multipart/form-data ?
> I already done parsing form parameters and sending GET/POST request,
> but does this work with <input type="file"> ?
> Who handle file submit and encoding ?
The XMLHttpRequest object has a method setRequestHeader so you would
need to set
httpRequestInstance.setRequestHeader(
'Content-Type: multipart/form-data')
at least after the open call, then you need to make sure your request
body, that is the string that you pass to the send method, is indeed in
the format multipart/form-data defines
<http://www.w3.org/TR/html4/interact/forms.html#h-17.13.4.2>.
If I understand that right then in reality you need to define a boundary
string used in the body to separate the multiple parts and you need to
pass the boundary string in the header so you would end up doing e.g.
var httpRequest = null;
if (typeof XMLHttpRequest != 'undefined') {
httpRequest = new XMLHttpRequest();
}
else if (typeof ActiveXObject != 'undefined') {
// need try/catch here in reality
httpRequest = new ActiveXObject('Microsoft.XMLHTTP');
}
if (httpRequest != null) {
var boundaryString = 'AaB03x';
var boundary = '--' + boundaryString;
var requestBody = [
boundary,
'Content-Disposition: form-data; name="GOD"',
'',
'Kibo',
boundary,
'Content-Disposition: file; name="prayer"; filename="prayer.txt"',
'Content-Type: text/plain',
'',
'Kibology for all.\r\nAll for Kibology.',
boundary
].join('\r\n');
httpRequest.open('POST', 'test2005093002.php', true);
if (typeof httpRequest.setRequestHeader != 'undefined') {
httpRequest.setRequestHeader('Content-Type',
'multipart/form-data; boundary=' + boundaryString);
httpRequest.onreadystatechange = function (evt) {
if (httpRequest.readyState == 4) {
alert(httpRequest.status + ' ' + httpRequest.statusText + '\r\n' +
httpRequest.getAllResponseHeaders() + '\r\n\r\n' +
httpRequest.responseText);
}
};
httpRequest.send(requestBody);
}
}
That simple example works for me here with IE 6, Mozilla 1.7, Opera 8.50
so that the PHP script receives the form data fine (one element in
$_POST and one in $_FILES).
Of course you have no way to read files from the local file system. And
encoding or binary data is not solved with that simple approach.
As for that prototype.js API, ask the author or look into its
documentation if one is provided.
--
Martin Honnen
http://JavaScript.FAQTs.com/