一个老外写的基于ajax的文本上传代码

Go_Rush 2006-06-07 10:32:31
当然,仅仅是文本文件,而且是事先知道内容。

对于以下问题,千万不要想歪了啊.
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/


...全文
589 6 打赏 收藏 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
wtogether 2006-06-08
  • 打赏
  • 举报
回复
xmlrpc.js
if (!window.XMLHttpRequest)
{
window.XMLHttpRequest = function()
{
if (window.ActiveXObject)
{
var list = new Array
(
"MSXML2.XMLHTTP.5.0",
"MSXML2.XMLHTTP.4.0",
"MSXML2.XMLHTTP.3.0",
"MSXML2.XMLHTTP.2.6",
"Microsoft.XMLHTTP"
);
for (var i = 0; i < list.length; i++)
{
try
{
return(new ActiveXObject(list[i]));
}
catch(ex)
{
}
}
}
return(null);
};
};

if (!window.XMLDOMDocument)
{
window.XMLDOMDocument = function()
{
if (window.ActiveXObject)
{
var list = new Array
(
"MSXML2.DOMDocument.4.0",
"MSXML2.DOMDocument.3.0",
"MSXML2.DOMDocument.2.6",
"Microsoft.XMLDOM"
);
for (var i = 0; i < list.length; i++)
{
try
{
return(new ActiveXObject(list[i]));
}
catch(ex)
{
}
}
}
else if (document.implementation && document.implementation.createDocument)
{
return(document.implementation.createDocument("", "", null));
}
return(null);
}
}

if (/gecko/i.test(window.navigator.userAgent))
{
Document.prototype.loadXML = function()
{
var xmldoc = (new DOMParser()).parseFromString(arguments[0], "text/xml");
while (this.hasChildNodes())
{
this.removeChild(this.lastChild);
}
for (var i = 0; i < xmldoc.childNodes.length; i++)
{
this.appendChild(this.importNode(xmldoc.childNodes[i], true));
}
return(true);
};
Document.prototype.selectSingleNode = function(tagname)
{
var node = this.evaluate(tagname, this, null, 0, null);
return(node.iterateNext());
};
Document.prototype.__defineGetter__("xml", function()
{
return((new XMLSerializer()).serializeToString(this));
});
Element.prototype.__defineGetter__("xml", function()
{
return (new XMLSerializer()).serializeToString(this);
});
Element.prototype.__defineGetter__("text", function()
{
return(this.textContent);
});
Element.prototype.__defineSetter__("text", function()
{
var argv = arguments;
this.textContent = argv[0];
});
}
wtogether 2006-06-08
  • 打赏
  • 举报
回复
借个地方发个WAP的web模拟器,楼主别见怪
非常简单的XMLHttpRequest和XMLDOMDocument应用,只能访问WAP页面,今天写这个模拟器的时候发现好多WAP站点的格式不规范,例如有的站点在xml前言上方还留有空行,这个是不被微软的XMLDOMDocument支持的,还有的页面包含 字符,这个是不被Firefox支持的

一共三个文件:xmlrpc.html xmlrpc.js xmlrpc.asp,放在同一个目录下,然后访问xmlrpc.html文件

xmlrpc.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
<meta http-equiv="content-type" content="text/html; charset=gb2312" />
<title>XMLRPC Demo</title>
<style type="text/css">
<!--
input, td, div {font-size:12px}
-->
</style>
<script language="javascript" src="xmlrpc.js"></script>
<script language="javascript">
<!--
var http = null;
var crtURL = "";

function loadWAP(strURL)
{
http = new XMLHttpRequest();
http.open("GET", strURL, true);
http.onreadystatechange = response;
http.send(null);
}

function toXML(strPtr)
{
var strTmp = strPtr.replace(/ /gi, " ");
var intPos = strTmp.indexOf("<");
if (intPos == -1) return(strTmp);
return(strTmp.substring(intPos, strTmp.length));
}

function getDomain()
{
/http:\/\/([^\/]*)/i.exec(crtURL);
return(RegExp.$1);
}

function getScript()
{
var idx = crtURL.lastIndexOf("/");
if (idx < 7 ) return(crtURL + "/");
return(crtURL.substring(0, idx + 1));
}

function toHTML(objRoot)
{
var objList = objRoot.getElementsByTagName("a");
for (var i = 0; i < objList.length; i++)
{
var strTmp = objList[i].getAttribute("href");
if (strTmp.substr(0, 7) == "http://")
{
objList[i].setAttribute("href", "javascript:doGet('" + strTmp + "')");
}
else if (strTmp.substr(0, 1) == "/")
{
objList[i].setAttribute("href", "javascript:doGet('http://" + getDomain() + strTmp + "')");
}
else
{
objList[i].setAttribute("href", "javascript:doGet('" + getScript() + strTmp + "')");
}
}
var objList = objRoot.getElementsByTagName("img");
for (var i = 0; i < objList.length; i++)
{
var strTmp = objList[i].getAttribute("src");
if (strTmp.substr(0, 7) == "http://")
{
}
else if (strTmp.substr(0, 1) == "/")
{
objList[i].setAttribute("src", "http://" + getDomain() + strTmp + "");
}
else
{
objList[i].setAttribute("src", "" + getScript() + strTmp + "");
}
}
return(objRoot.xml);
}

function response()
{
var obj = document.getElementById("WAP");
if (http.readyState == 1)
{
obj.innerHTML = "25%";
}
else if (http.readyState == 2)
{
obj.innerHTML = "50%";
}
else if (http.readyState == 3)
{
obj.innerHTML = "75%";
}
else if (http.readyState == 4)
{
obj.innerHTML = "100%";
try
{
if (http.status == 200)
{
var xml = new XMLDOMDocument();
xml.async = false;
if (xml.loadXML(toXML(http.responseText)))
{
var root = xml.selectSingleNode("/wml/card");
obj.innerHTML = toHTML(root);
}
else
{
obj.innerHTML = "Error Parse";
}
xml = null;
}
else
{
obj.innerHTML = "Error Response";
}
}
catch(ex)
{
obj.innerHTML = ex.description;
}
http = null;
var btn = document.getElementById("btnCall");
btn.disabled = false;
}
}

function WAPRequest()
{
try
{
var btn = document.getElementById("btnCall");
btn.disabled = true;
var obj = document.getElementById("WAP");
obj.innerHTML = "loading...";
crtURL = document.getElementById("strText").value;
loadWAP("xmlrpc.asp?URL=" + encodeURIComponent(crtURL));
}
catch(ex)
{
document.getElementById("WAP").innerHTML = ex.description;
}
}

function doGet(strURL)
{
document.getElementById("strText").value = strURL;
WAPRequest();
}
-->
</script>
</head>

<body>
<table width="180" border="1" cellpadding="2" cellspacing="0" bordercolor="#000000" style="border-collapse:collapse">
<tr>
<td bgcolor="#779DBF" style="color:#FFFFFF; padding-left:5px"><b>WAP模拟器</b></td>
</tr>
<tr>
<td>
<input type="text" id="strText" name="strText" style="border:1px solid #000000; height:14px; width:140px" />
<input type="button" id="btnCall" name="btnCall" value="GO" onclick="WAPRequest()" style="border:1px solid #000000; width:30px; padding:0px" />
</td>
</tr>
<tr>
<td><div id="WAP" style="border:1px solid #000000; padding:2px; width:180px; height:200px; overflow-y:auto; overflow-x:hidden"></div></td>
</tr>
</table>
</body>

</html>
jiangtao088 2006-06-08
  • 打赏
  • 举报
回复
问一下,AJAX是否只能上传文本型的文件。
Scarroot 2006-06-08
  • 打赏
  • 举报
回复
mark
boylez 2006-06-08
  • 打赏
  • 举报
回复
mark
wtogether 2006-06-07
  • 打赏
  • 举报
回复
去年在这里回答别人提问时,回过这样的上传文件代码,其实就是setRequestHeader应用,了解http协议就好办的,纯粹是发文本信息
代码下载链接: https://pan.quark.cn/s/a8fbca3925b4 《鸿蒙OS开发环境构建》指南系统性地阐述了配置和筹备鸿蒙OS开发所需的各种工具和条件的具体方法。鸿蒙OS,亦称HarmonyOS,是由华为研发的一款面向全场景的分布式操作系统,其目标是提供跨平台、多设备间无缝协作的使用体验。本指南涉及了从Linux服务器到Windows工作站的完整开发流程。指南中提及了MobaXterm,这是一款用于连接Linux源码服务器的软件,使得开发人员能够在Windows环境中远程访问Linux服务器。同时,HiTool作为烧录工具,用于将编译后的系统镜像入开发板。IPOP.EXE则是一款串口终端软件,用于执行串行通信和调试任务。Embedded Studio用于开发设备驱动程序,而DevEco Studio是华为提供的图形化应用程序开发平台,支持C/C++语言,拥有代码编辑、编译、烧录和调试功能,被视为OpenHarmony智能设备开发者的首选集成开发环境。在硬件配置方面,指南列出了必需的设备,包括Linux服务器(推荐Ubuntu 16.04及以上版本),Windows工作台(兼容XP/7/10),以及Hi3518EV300 IoT Camera单板。开发期间,Windows工作台通过USB线与单板相连接,以实现数据传输。此外,为了开展开发工作,还需要安装putty、IPOP、tftp服务器等辅助软件,以及HiTool用于烧录操作。在软件系统要求方面,Linux服务器需要安装bash、Python3.7+、gn、ninja、LLVM等构建工具,这些工具对于生成和执行编译脚本具有关键作用。在Windows工作台上,建议采用Visual Studi...

52,778

社区成员

发帖
与我相关
我的任务
社区描述
Web 开发 Ajax
社区管理员
  • Ajax
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧