控件的公共属性介绍完后,接下来是控件事件的处理,事件处理分为服务器事件和客户端事件处理,对于服务器端事件,除了在内部处理删除和上传的按钮点击事件外,组件还公开一个OnAfterOperation事件,当上传成功时或删除成功是触发该事件,而根据传给事件command名称可以判断是删除还是上传成功.之所以设置此事件,是考虑到今后的开发的filepicker作准备,其界面如下
当点击图片按钮时如下:
当该弹出窗口的上传下载组件每次操作成功后均应刷新预览窗口,因此设置此服务器端事件.
以下是具体的服务器端事件代码
server event#region server event
//处理删除按钮事件
private void Delete_Clicked(Object sender, System.Web.UI.ImageClickEventArgs e)
{
if(this.FileName!=string.Empty)
{
System.IO.File.Delete(this.Page.MapPath(this.FullFileName));
this.MessageBox("删除操作成功!");
this.FileName = string.Empty;
//成功时触发事件
OnAfterOperation(new CommandEventArgs("Delete",null));
}
}
//当操作成功时的弹出信息框
private void MessageBox(string strInfo)
{
strInfo="<script>alert('"+strInfo+"')</script>";
if(this.Page != null)
this.Page.RegisterStartupScript(System.Guid.NewGuid().ToString(),strInfo);
}
//初始化时将扩展名均化为小写字符便于今后验证
protected override void OnInit(EventArgs e)
{
base.OnInit (e);
foreach(StringItem item in this.ExtFilters)
{
item.Text = item.Text.ToLower();
}
}
//上传按钮事件
private void Upload_Clicked(Object sender, System.Web.UI.ImageClickEventArgs e)
{
System.Web.HttpPostedFile file = this.FileUpload.PostedFile;
string ExtName = file.FileName.Substring(file.FileName.LastIndexOf(".") + 1);
if(file.ContentLength > 0)
{
//服务器端文件类型验证
StringItem item = new StringItem();
item.Text = ExtName.ToLower();
if((this.ExtFilters.Count > 0)&&(!this.ExtFilters.Contains(item)))
{
this.MessageBox("文件类型不支持无法上传!");
return;
}
switch(this.UploadFileNameType)
{
case FileNameType.AutoGenerate:
//此时用guid的唯一性自动生成文件名
this.FileName = System.Guid.NewGuid().ToString() + "." + ExtName;
break;
case FileNameType.ClientSide:
//获取客户端文件名
this.FileName = file.FileName.Substring(file.FileName.LastIndexOf("\\")+1);
break;
}
if(this.FileName!=string.Empty)
{
file.SaveAs(this.Page.MapPath(this.FullFileName));
this.MessageBox("上传操作成功!");
//成功时触发事件
OnAfterOperation(new CommandEventArgs("Upload",null));
}
}
}
//事件键
private static readonly object EventOP = new object();
public event CommandEventHandler AfterOperation
{
add{ Events.AddHandler(EventOP,value); }
remove{ Events.RemoveHandler(EventOP,value); }
}
protected virtual void OnAfterOperation( CommandEventArgs e)
{
CommandEventHandler OpHandler = (CommandEventHandler)Events[EventOP];
if( OpHandler != null)
{
OpHandler(this,e);
}
}
#endregion