web开发,或多或少要用到上传文件的控件即 FileUpload 控件。现在的UI做的绚丽多彩,如果要上传图片,多少都要添加另外的功能。根据项目的需求,做个一个上传图片的自定义控件。
功能很简单,就是点击上传的小图图片,弹出层,已大图的形式显示。
功能描述:1、上传图片
2、小图显示图片
3、点击小图,浏览大图。
控件中使用了jquery 1.6脚本库。
在控件中添加了js代码。顺便记录下,在自定义控件中,封装JS,必须把js文件设置成嵌入的资源,即Embedded Resource。在自定义的项目中AssemblyInfo.cs文件中添加
[assembly: WebResource("UploadFile.publicjs.js", "text/javascript")] 。这个是必须的,要不然JS内容在自定义控件中找不到。
我再此自定义控件中使用的JS代码如下:
function Invoke() {
var img = $("#uploadedImage");
$("#addImg").attr("src", img.attr("src"));
}
$(document).ready(function () {
//动画速度
var speed = 500;
var imgDiv = $("#divPop");
imgDiv.hide(); //默认隐藏
var imgInfo = $("#uploadedImage");
//绑定事件处理
$("#uploadedImage").click(function (event) {
Invoke();
//取消事件冒泡
event.stopPropagation();
//设置弹出层位置
var offset = $(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) });
自定义控件代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace UploadFile
{
[DefaultProperty("UploadFile"), ToolboxData("<{0}:UploadFile runat=server></{0}:UploadFile>")] //自定控件 属性说明必不可少 而且属性名和类名必须一致
public class UploadFile : WebControl, INamingContainer
{
#region 域定义
private string _btnName = "上传";
private Unit _conlHeitht = new Unit(22);
private Unit _conlWidth = new Unit(320);
private Unit _btnWidth = new Unit(82);
private string _formerlyName = ""; //上传文件原来文件名称
private string _fileDownPath = ""; //要保存文件服务器上相对路径
private string _fileNameLoaded = "";//上传后的文件名
private string _fileType = "";
private string _fileDir = "";
private int _imgWidth = 30;
private int _imgHeight = 30;
private bool _imgVisible = false;
private bool _enabled = true;
private Unit _imgShowWidth = new Unit(30);
private Unit _imgShowHeight = new Unit(30);
private string _errorInfo = "";
private FileUpload fileUpload = new FileUpload();//上传控件
private Button _btnUpload = new Button();//上传按钮
private Image _image = new Image();//上传后显示控件
#endregion
#region 构造方法
public UploadFile()
{
this._btnUpload.ID = "btnUpload";
this._btnUpload.Click += new EventHandler(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 方法重写
protected override void Render(System.Web.UI.HtmlTextWriter output)
{
this.SetControlProperty();//设置控件的属性
this.RenderBeginTag(output);
this.fileUpload.RenderControl(output);
this._btnUpload.RenderControl(output);
this._image.RenderControl(output);
output.Write("<div id=\"divPop\" width=\"" + _imgShowWidth + "\" height=\"" + _imgShowHeight + "\" style=\"z-index: 9999\"><img id=\"addImg\" src=\"\"/>");
output.Write("<iframe src=\"\" 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,op acity=0)';\" width=\"" + _imgShowWidth + "\" height=\"" + _imgShowHeight + "\"></iframe>");
output.Write("</div>"); //在自定义控件中输出弹出层
this.RenderEndTag(output);
}
//将JS文件中的内容注册到自定义控件中
protected override void OnPreRender(EventArgs e)
{
ClientScriptManager csm = this.Page.ClientScript;
csm.RegisterClientScriptResource(typeof(UploadFile), "UploadFile.publicjs.js");
string sc = ScriptContent();
csm.RegisterClientScriptBlock(this.GetType(), "checkexpend", sc, true);
base.OnPreRender(e);
}
#endregion
#region 控件添加属性和事件
private void SetControlProperty()
{
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 = new Unit((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 = "单击查看大图";
}
public event EventHandler OnUploadClick;
private void btnUploadClick(object sender, EventArgs e)
{
EventArgs args = new EventArgs();
if (this.OnUploadClick != null)
{
SaveFile();
this.OnUploadClick(this._btnUpload, args);
}
}
#endregion
#region 自定义方法
private string ScriptContent()
{
StringBuilder strBuilder = new StringBuilder();
strBuilder.Append("function checkFileExpend(){");
strBuilder.Append("var fileObj = document.getElementById(\"fileUpload\");");
strBuilder.Append("var btnObj = document.getElementById(\"btnUpload\");");
strBuilder.Append("var v = fileObj.value;");
strBuilder.Append("var strV = \"" + _fileType.ToLower() + "\";");
strBuilder.Append("if(v!=\"\"){");
strBuilder.Append("var tmpImg = document.getElementById(\"uploadedImage\");");
strBuilder.Append("if(tmpImg!=null){");
strBuilder.Append("tmpImg.src=\"\";tmpImg.style.display = \"none\";");
strBuilder.Append("}");
strBuilder.Append("var len = v.length;var idex = v.lastIndexOf('.');");
strBuilder.Append("var exp = v.substr(idex+1,len-idex);");
strBuilder.Append("var idx = 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("function dbImage(){");
strBuilder.Append("var tmpObj = confirm(\"确认要删除此图片?\");");
strBuilder.Append("if(tmpObj){ alert(\"选择了删除\");");
strBuilder.Append("}}");
return strBuilder.ToString();
}
//保存文件
private void SaveFile()
{
string fileName = "";
bool res = CheckFile(out fileName);
if (res)
{
this._fileNameLoaded = fileName;
string relativePath = "";
_fileDownPath = GeneranyDir(out relativePath) + "/" + 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("上传文件格式不正确");
}
}
//服务器绝对目录
private string GeneranyDir(out string relativelyPath)
{
relativelyPath = "~/" + this._fileDir;
//虚拟目录映射到绝对目录
string serverPath = this.Page.Server.MapPath("~/" + this._fileDir + "/");
if (!Directory.Exists(serverPath))
{
Directory.CreateDirectory(serverPath);
}
return serverPath;
}
//检查文件
private bool CheckFile(out string fileName)
{
fileName = this.fileUpload.FileName;
_formerlyName = this.fileUpload.FileName;
bool isSuccess = false;
if (!string.IsNullOrEmpty(fileName))
{
int index = fileName.LastIndexOf('.');
string fileExp = fileName.Substring(index+1);
//生成新的文件名称
string newFileName = Guid.NewGuid().ToString();
fileName = string.Format("{0}.{1}", newFileName, fileExp);
int idx = this._fileType.IndexOf(fileExp);
//后缀名不匹配
if (idx != -1)
{
isSuccess= true;
}
}
return isSuccess;
}
private void ShowMessage(string infomation)
{
string sc = string.Format("$(function(){0}alert('{1}');{2})", "{", infomation, "}");
this.Page.ClientScript.RegisterStartupScript(this.Page.GetType(), "信息提示", sc, true);
}
#endregion
#region 扩展属性 只写属性在控件可视化中不显示
[Category("CustomProperty"),
Description("设置按钮文本内容")]
public string ButtonName
{
get
{
return this._btnName;
}
set
{
this._btnName = value;
}
}
[Category("CustomProperty"),
Description("设置控件的高度")]
public Unit ControlHeight
{
get
{
return this._conlHeitht;
}
set
{
this._conlHeitht = value;
}
}
[Category("CustomProperty"),
Description("设置控件的宽度")]
public Unit ControlWidth
{
get
{
return _conlWidth;
}
set
{
_conlWidth = value;
}
}
[Category("CustomProperty"),
Description("设置按钮的宽度")]
public Unit ButtonWidth
{
get
{
return _btnWidth;
}
set
{
_btnWidth = value;
}
}
[Category("FileExpend"),
Description("只读属性,返回文件上传成功后文件绝对路径")]
public string GetUploadedFilePath
{
get
{
return this._fileDownPath;
}
}
[Category("FileExpend"),
Description("文件扩展名格式,多个用逗号隔开jpg,jpeg,bmp等")]
public string UpFileType
{
get
{
return _fileType;
}
set
{
_fileType = value;
}
}
[Category("ErrorInfo"),
Description("文件格式不正确,弹出框提示信息")]
public string ErrorInfomation
{
get
{
return _errorInfo;
}
set
{
_errorInfo = value;
}
}
[Category("FileExpend"),
Description("上传文件存放的目录")]
public string FileStoredDir
{
get
{
return this._fileDir;
}
set
{
_fileDir = value;
}
}
[Category("FileExpend"),
Description("只读属性 上传完成后的文件名称")]
public string LoadedFileName
{
get
{
return _fileNameLoaded;
}
}
[Category("FileExpend"),
Description("只读属性 上传文件原来名称")]
public string FormerlyFileName
{
get
{
return _formerlyName;
}
}
[Category("ImageAttribute"),
Description("设置图片的宽度")]
public int ImageWidth
{
get
{
return this._imgWidth;
}
set
{
this._imgWidth = value;
}
}
[Category("ImageAttribute"),
Description("设置图片的宽度")]
public int ImageHeight
{
get
{
return this._imgHeight;
}
set
{
this._imgHeight = value;
}
}
[Category("ImageAttribute"),
Description("是否显示图片")]
public bool ImageVisible
{
get
{
return this._imgVisible;
}
set
{
this._imgVisible = value;
}
}
[Category("ImageAttribute"),
Description("设置图片相对路径")]
public string ImageUrlPath
{
get
{
return _image.ImageUrl;
}
set
{
if (!string.IsNullOrEmpty(value))
{
_imgVisible = true;
_image.ImageUrl = value;
}
}
}
[Category("ImageAttribute"),
Description("浏览时图片宽度")]
public Unit ImageShowWidth
{
get
{
return _imgShowWidth;
}
set
{
_imgShowWidth = value;
}
}
[Category("ImageAttribute"),
Description("浏览时图片高度")]
public Unit ImageShowHeight
{
get
{
return _imgShowHeight;
}
set
{
_imgShowHeight = value;
}
}
[Category("FileExpend"),
Description("设置控件是否可用")]
public bool UpEnabled
{
get
{
return _enabled;
}
set
{
_enabled = value;
}
}
#endregion
}
}
});
UpFileType属性,这是要上传图片的格式,如果多种图用逗号隔开,例如:jpeg,jpg,bmp

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

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

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

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