使用客户端回调的确认框(文件替换)
询问用户是否替换文件。
引言
您正在提供一种将文件上传到Web服务器的功能。客户端可以上传任何文件。客户端不知道他上传的文件是否已经存在于Web服务器上。因此,您需要检查并询问是否要替换现有文件。
一旦用户选择了文件,我们需要检查该文件是否已存在于Web服务器上。
为此进行完全回发会导致FileUpload
控件中的文件丢失。由于页面及其控件将被重新创建,页面代码将在服务器上运行,并且将向浏览器呈现页面的新版本。
只有在保存文件时才会进行完全回发。
背景
为了避免丢失客户端状态并避免服务器往返处理的开销,您可以编写一个ASP.NET Web页面,使其能够执行客户端回调。在客户端回调中,客户端脚本函数将请求发送到ASP.NET Web页面。Web页面运行其正常生命周期的修改版本。页面被初始化,其控件和其他成员被创建,然后调用一个特别标记的方法。该方法执行您编写的处理,然后将一个值返回到浏览器,该值可以由另一个客户端脚本函数读取。在整个过程中,页面都处于浏览器中活动状态。
Using the Code
<asp:FileUpload ID="FileUpload1" runat="server" />
<input type="button" id="hBtn" value="Save" onclick="CheckFile()" />
<asp:Button ID="btnSave" runat="server" Text="Save" onclick="btnSave_Click" />
<asp:HiddenField ID="hdnIsOverwrite" runat="server" />
public partial class _Default : System.Web.UI.Page,
System.Web.UI.ICallbackEventHandler
{
protected bool returnValue;
protected void Page_Load(object sender, EventArgs e)
{
// hide server side button
btnSave.Style.Add(HtmlTextWriterStyle.Display, "none");
String cbReference =
Page.ClientScript.GetCallbackEventReference(this,
"arg", "ReceiveServerData", "context","processError",false);
String callbackScript;
callbackScript = "function CallServer(arg, context)" +
"{ " + cbReference + ";}";
Page.ClientScript.RegisterClientScriptBlock(this.GetType(),
"CallServer", callbackScript, true);
}
protected void btnSave_Click(object sender, EventArgs e)
{
FileUpload1.PostedFile.SaveAs(Server.MapPath
(Path.GetFileName(FileUpload1.PostedFile.FileName)));
}
public void RaiseCallbackEvent(String eventArgument)
{
//dummy processing
System.Threading.Thread.Sleep(5000);
//set return value
returnValue = File.Exists(Server.MapPath(Path.GetFileName(eventArgument)));
}
public String GetCallbackResult()
{
return returnValue.ToString().ToLower();
}
}
<script language="javascript" type="text/javascript">
function CheckFile()
{
var fu= document.getElementById("FileUpload1");
var btn = document.getElementById("hBtn");
if(fu.value=='')
{
alert('Please select a file.');
fu.focus();
}
else
{
//fire request to server
CallServer(fu.value,"filename");
btn.disabled=true;
}
}
function ReceiveServerData(rValue)
{
var fu= document.getElementById("FileUpload1");
var btnServer = document.getElementById("btnSave");
var btn = document.getElementById("hBtn");
//disable the button for further clicking
btn.disabled=false;
if(rValue=='true') // file exists
{
if(confirm('Are you sure you want to replace the file ?'))
{
document.getElementById("hdnIsOverwrite").value="true";
//save file , you can also use __doPostback()
btnServer.click();
}
}
else
{
document.getElementById("hdnIsOverwrite").value="false";
//save file , you can also use __doPostback()
btnServer.click();
}
}
function processError(rValue)
{
alert(rValue);
}
</script>
关注点
ClientCallback
的一个很好的用例
历史
- 2009年5月25日:初始发布