使用Anthem.NET 1.5中的FileUpload控件实现Ajax方式的文件上传
2015-12-02 20:33
776 查看
Anthem.NET的下载与安装
Anthem.NET可以在此下载:
下载之后解压缩至硬盘中的某一目录中,编译项目得到Anthem.dll。然后将其拷贝到Web站点的bin目录下:
打开Web站点的Web.config文件,在configuration>\<system.web>\<pages>\<controls>中添加如下一行,注册Anthem.NET控件:
<addtagPrefix="anthem"namespace="Anthem"assembly="Anthem"/>
Anthem.NET提供了一套自己就带有Ajax功能的、继承于现有ASP.NET控件的服务器端控件。根据上面在web.config文件中的注册,这部分控件的前缀为anthem。
Anthem.NET支持ASP.NET1.1和ASP.NET2.0,不过本文的示例程序均基于ASP.NET2.0。
普通的ASP.NET文件上传
先看一下普通的ASP.NET文件上传功能的实现,代码如下:
<asp:FileUploadID="defaultFileUpload"runat="server"/>
[code]<asp:ButtonID="defaultUploadButton"runat="server"
OnClick="defaultUploadButton_Click"Text="Upload"/>
<asp:LabelID="defaultResultLabel"runat="server"Text=""></asp:Label>
[/code]
后台代码,只是简单地将文件名和文件大小显示出来:
protectedvoiddefaultUploadButton_Click(objectsender,EventArgse)
[code]{
defaultResultLabel.Text=string.Format("File\"{0}\"uploaded({1}bytes).",
defaultFileUpload.FileName,
defaultFileUpload.FileBytes.Length
);
}
[/code]
Anthem.NET的Ajax文件上传
Anthem.NET中的Ajax文件上传功能靠的是其自己的FileUpload控件,其实使用起来和普通的ASP.NETFileUpload控件差不多,下面是HTML部分的代码:
<anthem:FileUploadID="anthemFileUpload"runat="server"/>
[code]<anthem:ButtonID="anthemUploadButton"TextDuringCallBack="uploading..."EnabledDuringCallBack="false"
runat="server"Text="Upload"OnClick="anthemUploadButton_Click"/>
<anthem:LabelID="anthemResultLabel"runat="server"Text=""></anthem:Label>
[/code]
注意控件的前缀都是anthem。那个Button的TextDuringCallBack属性设置了异步回送时按钮中的文本;EnabledDuringCallBack属性让该按钮在进行异步回送时禁用,免得用户等得不耐烦。
后台代码同样是将文件名和文件大小显示出来,不过注意这一句anthemResultLabel.UpdateAfterCallBack=true;,用来在回调之后更新anthemResultLabel上的文字:
protectedvoidanthemUploadButton_Click(objectsender,EventArgse)
[code]{
anthemResultLabel.Text=string.Format("File\"{0}\"uploaded({1}bytes).",
anthemFileUpload.FileName,
anthemFileUpload.FileBytes.Length
);
anthemResultLabel.UpdateAfterCallBack=true;
}
[/code]
示例程序演示
示例程序的界面如下,上面部分是普通的ASP.NET文件上传,下面是Anthem.NET的Ajax文件上传:
使用普通的ASP.NET文件上传,可以看到页面有一次闪烁,不过上传功能没什么问题:
而使用下面部分的Anthem.NET的Ajax文件上传,可以看到上传时的界面(按钮禁用,文本变化):
上传完成之后,没有页面闪烁:
打开Fiddler看看HTTP请求,上面的是传统上传,下面是Ajax的,差别显而易见……
代码下载
本文提到的完整的示例程序代码:
更多参考资料
Anthem.NET官方网站:
Anthem.NET在线文档:
Anthem.NET在线示例程序:
Fiddler官方网站:
tojeff(实现方式)
除了用IFrame,还有什么好办法么?它也是用的IFrame,相关代码如下:注意58-61,109-113,131-148这几段(粗体部分)。
有空的时候改到Atlas里面吧,呵呵,造福群众阿
functionAnthem_CallBack(url,target,id,method,args,clientCallBack,clientCallBackArg,includeControlValuesWithCallBack,updatePageAfterCallBack){
[code]if(typeof(window.Anthem_PreCallBack)=="function"){
varpreCallBackResult=Anthem_PreCallBack();
if(!(typeofpreCallBackResult=="undefined"||preCallBackResult)){
if(typeof(window.Anthem_CallBackCancelled)=="function"){
Anthem_CallBackCancelled();
}
returnnull;
}
}
varencodedData="";
if(target=="Page"){
encodedData+="&Anthem_PageMethod="+method;
}elseif(target=="MasterPage"){
encodedData+="&Anthem_MasterPageMethod="+method;
}elseif(target=="Control"){
encodedData+="&Anthem_ControlID="+id.split(":").join("_");
encodedData+="&Anthem_ControlMethod="+method;
}
if(args){
for(varargsIndex=0;argsIndex<args.length;++argsIndex){
if(args[argsIndex]instanceofArray){
for(vari=0;i<args[argsIndex].length;++i){
encodedData+="&Anthem_CallBackArgument"+argsIndex+"="+Anthem_Encode(args[argsIndex][i]);
}
}else{
encodedData+="&Anthem_CallBackArgument"+argsIndex+"="+Anthem_Encode(args[argsIndex]);
}
}
}
if(updatePageAfterCallBack){
encodedData+="&Anthem_UpdatePage=true";
}
//AnthemwillnormallyuseanXmlHttpRequesttocommunicatewiththeserver.
//ButifanAnthem.FileUploadcontrolisdiscoveredonthepage,thenAnthem
//willuseahiddenIFRAMEinstead.ThishiddenIFRAMEisoftencalledanIOFrame
//byAJAXlibraryauthors,sothatisthenameweusehere.
varuseIOFrame=false;
//Scanthecontrolsontheformandextracttheirvalues.
if(includeControlValuesWithCallBack){
varform=Anthem_GetForm();
if(form!=null){
for(varelementIndex=0;elementIndex<form.length;++elementIndex){
varelement=form.elements[elementIndex];
if(element.name){
varelementValue=null;
if(element.nodeName.toUpperCase()=="INPUT"){
varinputType=element.getAttribute("type").toUpperCase();
if(inputType=="TEXT"||inputType=="PASSWORD"||inputType=="HIDDEN"){
elementValue=element.value;
}elseif(inputType=="CHECKBOX"||inputType=="RADIO"){
if(element.checked){
elementValue=element.value;
}
}elseif(inputType=="FILE"){
//IftheFILEelementhasavalue(thepathtothefile),thenan
//IOFramewillbeusedtohandlethecallback.
useIOFrame=useIOFrame|!(element.value==null||element.value.length==0);
}
}elseif(element.nodeName.toUpperCase()=="SELECT"){
if(element.multiple){
elementValue=[];
for(vari=0;i<element.length;++i){
if(element.options[i].selected){
elementValue.push(element.options[i].value);
}
}
}elseif(element.length==0){
elementValue=null;
}else{
elementValue=element.value;
}
}elseif(element.nodeName.toUpperCase()=="TEXTAREA"){
elementValue=element.value;
}
if(elementValueinstanceofArray){
for(vari=0;i<elementValue.length;++i){
encodedData+="&"+element.name+"="+Anthem_Encode(elementValue[i]);
}
}elseif(elementValue!=null){
encodedData+="&"+element.name+"="+Anthem_Encode(elementValue);
}
}
}
//ASP.NET1.1won'tfireanyeventsifneitherofthefollowing
//twoparametersarenotintherequestsomakesurethey're
//alwaysintherequest.
if(typeofform.__VIEWSTATE=="undefined"){
encodedData+="&__VIEWSTATE=";
}
if(typeofform.__EVENTTARGET=="undefined"){
encodedData+="&__EVENTTARGET=";
}
}
}
if(encodedData.length>0){
encodedData=encodedData.substring(1);
}
if(typeof(Anthem_DebugRequestText)=="function"){
Anthem_DebugRequestText(encodedData.split("&").join("\n&"));
}
//Sendthecallbackrequesttotheserver.UseanIOFrameifthereisafileupload,
//otherwiseuseanXmlHttpRequest.
if(useIOFrame){
//Toallowmultiplerequestsatthesametime,alloftheAnthemparametersare
//passedtotheserverviathequerystring
varaction=Anthem_GetCallBackUrl();
action=action+"&Anthem_IOFrame=true";
if(updatePageAfterCallBack){
action=action+"&Anthem_UpdatePage=true";
}
//WecouldgenerateananonymousfunctionontheflytohandletheclientCallBack
//andassignthattotheiframeonloadevent(infactthisishowXmlHttpRequestsare
//handled).Butthatmakesitveryhardtodebugthecallbackresponse.Instead
//wewillstufftheclientCallBackfunctionandargsintoanarrayandthenhardcode
//theonloadeventhandler.Thehandlerwillfindtheappropriatecallbackinfoin
//thearrayandhandletheclientCallBack.
varid="f"+newString(Math.floor(9999*Math.random()));//Generateframenumber
if(typeof(clientCallBack)=="function"){
varframe={"id":id,"clientCallBack":clientCallBack,"clientCallBackArg":clientCallBackArg};
callbackFrames.push(frame);
}
//Createanew,invisibleiframetohandletheio.
varioframe=null;
if(window.ActiveXObject){
ioframe=document.createElement("<iframename=\""+id+"\"id=\""+id+"\"onload=\"Anthem_HandleIOFrameResponse('"+id+"');\"/>");
}else{
ioframe=document.createElement("iframe");
ioframe.id=id;
ioframe.name=id;
ioframe.onload=function(){Anthem_HandleIOFrameResponse(id);}
}
ioframe.style.visibility="hidden";
ioframe.style.height="1px";
document.body.appendChild(ioframe);
//Submitthisforminthehiddeniframe
vartheForm=Anthem_GetForm();
vartempActionUri=theForm.action;
theForm.action=action;
theForm.target=id;
try{
theForm.submit();
}catch(e){
result={"value":null,"error":e.message};
if(typeof(Anthem_DebugError)=="function"){
Anthem_DebugError(e.name+":"+e.message+"("+e.number+")");
}
if(typeof(window.Anthem_Error)=="function"){
Anthem_Error(result);
}
}
//Restoretheform
theForm.target="";
theForm.action=tempActionUri;
}else{
varx=Anthem_GetXMLHttpRequest();
varresult=null;
if(!x){
result={"value":null,"error":"NOXMLHTTP"};
if(typeof(Anthem_DebugError)=="function"){
Anthem_DebugError(result.error);
}
if(typeof(window.Anthem_Error)=="function"){
Anthem_Error(result);
}
if(typeof(clientCallBack)=="function"){
clientCallBack(result,clientCallBackArg);
}
returnresult;
}
varaction=Anthem_GetCallBackUrl();
x.open("POST",url?url:action,clientCallBack?true:false);
x.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=utf-8");
x.setRequestHeader("Accept-Encoding","gzip,deflate");
if(typeof(clientCallBack)=="function"){
x.onreadystatechange=function(){
if(x.readyState!=4){
return;
}
if(typeof(Anthem_DebugResponseText)=="function"){
Anthem_DebugResponseText(x.responseText);
}
result=Anthem_GetResult(x);
if(result.error){
if(typeof(Anthem_DebugError)=="function"){
Anthem_DebugError(result.error);
}
if(typeof(window.Anthem_Error)=="function"){
Anthem_Error(result);
}
}
if(updatePageAfterCallBack){
Anthem_UpdatePage(result);
}
Anthem_EvalClientSideScript(result);
clientCallBack(result,clientCallBackArg);
x=null;
if(typeof(window.Anthem_PostCallBack)=="function"){
Anthem_PostCallBack();
}
}
}
x.send(encodedData);
if(typeof(clientCallBack)!="function"){
if(typeof(Anthem_DebugResponseText)=="function"){
Anthem_DebugResponseText(x.responseText);
}
result=Anthem_GetResult(x);
if(result.error){
if(typeof(Anthem_DebugError)=="function"){
Anthem_DebugError(result.error);
}
if(typeof(window.Anthem_Error)=="function"){
Anthem_Error(result);
}
}
if(updatePageAfterCallBack){
Anthem_UpdatePage(result);
}
Anthem_EvalClientSideScript(result);
if(typeof(window.Anthem_PostCallBack)=="function"){
Anthem_PostCallBack();
}
}
}
returnresult;
}
[/code]
出处:
相关文章推荐
- 基站与终端流量的需求问题处理
- 字典转模型
- (十四)关于#include<iostream>
- spring容器DI依赖注入对象<三>
- PHP构造JSon数据的两种方法
- 实践与理论的思考
- mathematica练习程序(图像取反)
- 实验三 进程调度模拟程序
- XSS攻击及防御
- UBIFS介绍 raw flash和MMC flash的区别
- 初识Qualcomm Adreno SDK
- 复习Android中webView和JavaScript的交互
- mac键盘图表大全
- runtime运行机制
- 商务通隐藏默认邀请框代码
- 翻转单词顺序列(C++)
- JDBC--调用函数&存错过程
- 【openjudge】买书
- 要开始写博客了
- 【MongoDB系列】:MongoDB介绍和安装