您的位置:首页 > 其它

基于VS2010的上传文件控件

2012-01-14 13:45 204 查看
web开发,或多或少要用到上传文件的控件即FileUpload控件。现在的UI做的绚丽多彩,如果要上传图片,多少都要添加另外的功能。根据项目的需求,做个一个上传图片的自定义控件。
功能很简单,就是点击上传的小图图片,弹出层,已大图的形式显示。
功能描述:1、上传图片

2、小图显示图片

3、点击小图,浏览大图。

控件中使用了jquery1.6脚本库。

在控件中添加了js代码。顺便记录下,在自定义控件中,封装JS,必须把js文件设置成嵌入的资源,即EmbeddedResource。在自定义的项目中AssemblyInfo.cs文件中添加

[assembly:WebResource("UploadFile.publicjs.js","text/javascript")]。这个是必须的,要不然JS内容在自定义控件中找不到。

我再此自定义控件中使用的JS代码如下:

functionInvoke(){
varimg=$("#uploadedImage");
$("#addImg").attr("src",img.attr("src"));
}
$(document).ready(function(){
//动画速度
varspeed=500;
varimgDiv=$("#divPop");
imgDiv.hide();//默认隐藏
varimgInfo=$("#uploadedImage");
//绑定事件处理
$("#uploadedImage").click(function(event){
Invoke();
//取消事件冒泡
event.stopPropagation();
//设置弹出层位置
varoffset=$(event.target).offset();
$("#divPop")
.css({"position":"absolute"})
.animate({
"opacity":"show",
"height":imgDiv.height()+"px",
"width":imgDiv.width()+"px",
"top":"100px",
"left":"100px"
},"show");
//动画显示
$("#divPop").show(speed);
});
//单击空白区域隐藏弹出层
$(document).click(function(event){$("#divPop").hide(speed)});
//单击弹出层则自身隐藏
$("#divPop").click(function(event){$("#divPop").hide(speed)});
自定义控件代码:
usingSystem;
usingSystem.Collections.Generic;
usingSystem.ComponentModel;
usingSystem.IO;
usingSystem.Text;
usingSystem.Web.UI;
usingSystem.Web.UI.WebControls;

namespaceUploadFile
{
[DefaultProperty("UploadFile"),ToolboxData("<{0}:UploadFilerunat=server></{0}:UploadFile>")]//自定控件属性说明必不可少而且属性名和类名必须一致
publicclassUploadFile:WebControl,INamingContainer
{
#region域定义
privatestring_btnName="上传";

privateUnit_conlHeitht=newUnit(22);
privateUnit_conlWidth=newUnit(320);
privateUnit_btnWidth=newUnit(82);

privatestring_formerlyName="";//上传文件原来文件名称
privatestring_fileDownPath="";//要保存文件服务器上相对路径
privatestring_fileNameLoaded="";//上传后的文件名
privatestring_fileType="";
privatestring_fileDir="";
privateint_imgWidth=30;
privateint_imgHeight=30;
privatebool_imgVisible=false;
privatebool_enabled=true;

privateUnit_imgShowWidth=newUnit(30);
privateUnit_imgShowHeight=newUnit(30);

privatestring_errorInfo="";

privateFileUploadfileUpload=newFileUpload();//上传控件
privateButton_btnUpload=newButton();//上传按钮
privateImage_image=newImage();//上传后显示控件
#endregion

#region构造方法
publicUploadFile()
{
this._btnUpload.ID="btnUpload";
this._btnUpload.Click+=newEventHandler(this.btnUploadClick);

this.fileUpload.ID="fileUpload";
this.fileUpload.Attributes.Add("onchange","javascript:checkFileExpend();");

this._image.ID="uploadedImage";
//this._image.Attributes.Add("ondblclick","javascript:dbImage();");

this.Controls.Add(this._btnUpload);//在自定义控件中添加控件
this.Controls.Add(this.fileUpload);
this.Controls.Add(this._image);
}
#endregion

#region方法重写
protectedoverridevoidRender(System.Web.UI.HtmlTextWriteroutput)
{
this.SetControlProperty();//设置控件的属性
this.RenderBeginTag(output);

this.fileUpload.RenderControl(output);
this._btnUpload.RenderControl(output);
this._image.RenderControl(output);
output.Write("<divid=\"divPop\"width=\""+_imgShowWidth+"\"height=\""+_imgShowHeight+"\"style=\"z-index:9999\"><imgid=\"addImg\"src=\"\"/>");
output.Write("<iframesrc=\"\"frameborder=\"0\"style=\"position:absolute;visibility:inherit;top:1px;left:1px;width:100%;height:100%;z-index:-1;filter='progid:DXImageTransform.Microsoft.Alpha(style=0,opacity=0)';\"width=\""+_imgShowWidth+"\"height=\""+_imgShowHeight+"\"></iframe>");
output.Write("</div>");//在自定义控件中输出弹出层

this.RenderEndTag(output);
}

//将JS文件中的内容注册到自定义控件中
protectedoverridevoidOnPreRender(EventArgse)
{
ClientScriptManagercsm=this.Page.ClientScript;
csm.RegisterClientScriptResource(typeof(UploadFile),"UploadFile.publicjs.js");
stringsc=ScriptContent();
csm.RegisterClientScriptBlock(this.GetType(),"checkexpend",sc,true);
base.OnPreRender(e);
}
#endregion

#region控件添加属性和事件
privatevoidSetControlProperty()
{
this._btnUpload.Text=this._btnName;
this._btnUpload.Height=this._conlHeitht;
this._btnUpload.Enabled=false;
this._btnUpload.Width=this._btnWidth;
this.fileUpload.Width=this._conlWidth;
this.fileUpload.Width=newUnit((this._conlWidth.Value-this._btnWidth.Value));

this._image.Height=this._imgHeight;
this._image.Width=this._imgWidth;
this._image.Visible=this._imgVisible;
this.fileUpload.Enabled=this._enabled;
this._image.ToolTip="单击查看大图";
}

publiceventEventHandlerOnUploadClick;

privatevoidbtnUploadClick(objectsender,EventArgse)
{
EventArgsargs=newEventArgs();
if(this.OnUploadClick!=null)
{
SaveFile();
this.OnUploadClick(this._btnUpload,args);
}
}
#endregion

#region自定义方法
privatestringScriptContent()
{
StringBuilderstrBuilder=newStringBuilder();

strBuilder.Append("functioncheckFileExpend(){");
strBuilder.Append("varfileObj=document.getElementById(\"fileUpload\");");
strBuilder.Append("varbtnObj=document.getElementById(\"btnUpload\");");
strBuilder.Append("varv=fileObj.value;");
strBuilder.Append("varstrV=\""+_fileType.ToLower()+"\";");
strBuilder.Append("if(v!=\"\"){");
strBuilder.Append("vartmpImg=document.getElementById(\"uploadedImage\");");
strBuilder.Append("if(tmpImg!=null){");
strBuilder.Append("tmpImg.src=\"\";tmpImg.style.display=\"none\";");
strBuilder.Append("}");
strBuilder.Append("varlen=v.length;varidex=v.lastIndexOf('.');");
strBuilder.Append("varexp=v.substr(idex+1,len-idex);");
strBuilder.Append("varidx=strV.indexOf(exp.toLowerCase());");
strBuilder.Append("if(idx==-1){");
strBuilder.Append("btnObj.disabled=true;");
strBuilder.Append("}else{");
strBuilder.Append("btnObj.disabled=false;");
strBuilder.Append("}}}");

strBuilder.Append("functiondbImage(){");
strBuilder.Append("vartmpObj=confirm(\"确认要删除此图片?\");");
strBuilder.Append("if(tmpObj){alert(\"选择了删除\");");
strBuilder.Append("}}");
returnstrBuilder.ToString();
}
//保存文件
privatevoidSaveFile()
{
stringfileName="";
boolres=CheckFile(outfileName);
if(res)
{
this._fileNameLoaded=fileName;
stringrelativePath="";
_fileDownPath=GeneranyDir(outrelativePath)+"/"+fileName;
this._image.ImageUrl=string.Format("{0}/{1}",relativePath,fileName);
if(_fileDownPath.Length<=250)
{
this.fileUpload.SaveAs(_fileDownPath);
this._imgVisible=true;

ShowMessage("上传文件成功");
}
else
{
ShowMessage("上传文件名太长");
}
}
else
{
ShowMessage("上传文件格式不正确");
}
}
//服务器绝对目录
privatestringGeneranyDir(outstringrelativelyPath)
{
relativelyPath="~/"+this._fileDir;
//虚拟目录映射到绝对目录
stringserverPath=this.Page.Server.MapPath("~/"+this._fileDir+"/");
if(!Directory.Exists(serverPath))
{
Directory.CreateDirectory(serverPath);
}
returnserverPath;
}
//检查文件
privateboolCheckFile(outstringfileName)
{
fileName=this.fileUpload.FileName;
_formerlyName=this.fileUpload.FileName;
boolisSuccess=false;
if(!string.IsNullOrEmpty(fileName))
{
intindex=fileName.LastIndexOf('.');
stringfileExp=fileName.Substring(index+1);

//生成新的文件名称
stringnewFileName=Guid.NewGuid().ToString();
fileName=string.Format("{0}.{1}",newFileName,fileExp);

intidx=this._fileType.IndexOf(fileExp);
//后缀名不匹配
if(idx!=-1)
{
isSuccess=true;
}
}
returnisSuccess;
}

privatevoidShowMessage(stringinfomation)
{
stringsc=string.Format("$(function(){0}alert('{1}');{2})","{",infomation,"}");
this.Page.ClientScript.RegisterStartupScript(this.Page.GetType(),"信息提示",sc,true);
}
#endregion

#region扩展属性只写属性在控件可视化中不显示
[Category("CustomProperty"),
Description("设置按钮文本内容")]
publicstringButtonName
{
get
{
returnthis._btnName;
}
set
{
this._btnName=value;
}
}

[Category("CustomProperty"),
Description("设置控件的高度")]
publicUnitControlHeight
{
get
{
returnthis._conlHeitht;
}
set
{
this._conlHeitht=value;
}
}

[Category("CustomProperty"),
Description("设置控件的宽度")]
publicUnitControlWidth
{
get
{
return_conlWidth;
}
set
{
_conlWidth=value;
}
}
[Category("CustomProperty"),
Description("设置按钮的宽度")]
publicUnitButtonWidth
{
get
{
return_btnWidth;
}
set
{
_btnWidth=value;
}
}

[Category("FileExpend"),
Description("只读属性,返回文件上传成功后文件绝对路径")]
publicstringGetUploadedFilePath
{
get
{
returnthis._fileDownPath;
}
}
[Category("FileExpend"),
Description("文件扩展名格式,多个用逗号隔开jpg,jpeg,bmp等")]
publicstringUpFileType
{
get
{
return_fileType;
}
set
{
_fileType=value;
}
}

[Category("ErrorInfo"),
Description("文件格式不正确,弹出框提示信息")]
publicstringErrorInfomation
{
get
{
return_errorInfo;
}
set
{
_errorInfo=value;
}
}

[Category("FileExpend"),
Description("上传文件存放的目录")]
publicstringFileStoredDir
{
get
{
returnthis._fileDir;
}
set
{
_fileDir=value;
}
}

[Category("FileExpend"),
Description("只读属性上传完成后的文件名称")]
publicstringLoadedFileName
{
get
{
return_fileNameLoaded;
}
}

[Category("FileExpend"),
Description("只读属性上传文件原来名称")]
publicstringFormerlyFileName
{
get
{
return_formerlyName;
}
}

[Category("ImageAttribute"),
Description("设置图片的宽度")]
publicintImageWidth
{
get
{
returnthis._imgWidth;
}
set
{
this._imgWidth=value;
}
}

[Category("ImageAttribute"),
Description("设置图片的宽度")]
publicintImageHeight
{
get
{
returnthis._imgHeight;
}
set
{
this._imgHeight=value;
}
}

[Category("ImageAttribute"),
Description("是否显示图片")]
publicboolImageVisible
{
get
{
returnthis._imgVisible;
}
set
{
this._imgVisible=value;
}
}

[Category("ImageAttribute"),
Description("设置图片相对路径")]
publicstringImageUrlPath
{
get
{
return_image.ImageUrl;
}
set
{
if(!string.IsNullOrEmpty(value))
{
_imgVisible=true;
_image.ImageUrl=value;
}
}
}

[Category("ImageAttribute"),
Description("浏览时图片宽度")]
publicUnitImageShowWidth
{
get
{
return_imgShowWidth;
}
set
{
_imgShowWidth=value;
}
}

[Category("ImageAttribute"),
Description("浏览时图片高度")]
publicUnitImageShowHeight
{
get
{
return_imgShowHeight;
}
set
{
_imgShowHeight=value;
}
}

[Category("FileExpend"),
Description("设置控件是否可用")]
publicboolUpEnabled
{
get
{
return_enabled;
}
set
{
_enabled=value;
}
}
#endregion
}
}
});
UpFileType属性,这是要上传图片的格式,如果多种图用逗号隔开,例如:jpeg,jpg,bmp


控件默认上传按钮为灰色,如果选择的图片符合设置,上传按钮才可用使用。


点击上传,如果上传成功,提示信息,并显示图片。


点击小图,将弹出层,浏览大图。


点击弹出的层,或者其他空白地方,弹出的层自动隐藏。
总结:1、控件中使用了jquery框架,简化了很多js代码。而且弹出的层在IE6下,也可以遮挡下拉列表。其中使用了iframe。
2、提供常用的设置属性,设置图片的存放路径、显示大小。
3、提供外部方法,接受上传图片后的存放路径,和上传后图片的名称。
上传图片控件,只是项目中用到的一部分控件,其实在项目中,都把控件封装成自己需求的,也未尝不是件痛快事。加上校验规则,就可以成为公共控件,以后使用就方便多了。








                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: