1 using System.Web.UI.HtmlControls; 2 using System.Configuration; 3 using System.ComponentModel; 4 using System.Web.Security; 5 using System.Security.Principal; 6 using System.Drawing; 7 using System.Drawing.Text; 8 using System.Collections; 9 using System.Collections.Specialized; 10 11 namespace Rungoo.WebCtrlLib 12 { 13 /**//// <summary> 14 /// 文件上传控件 15 /// Author: nowind 16 /// Date: 2006-3-4 17 /// Email: hgh113@sina.com 18 /// QQ: 87505959 19 /// </summary> 20 [DefaultProperty("Text"), 21 ToolboxData("<{0}:WebUploadFile runat=server></{0}:WebUploadFile>")] 22 public class WebUploadFile : System.Web.UI.WebControls.WebControl,INamingContainer 23 { 24 private event EventHandler uploaded; 25 26 属性#region 属性 27 28 机器属性#region 机器属性 29 /**//// <summary> 30 /// 域 31 /// </summary> 32 [Bindable(true), 33 Category("Data"),Description("图片存放目标计算机的IP或者机器名,只在跨计算机上传时候填写"), 34 DefaultValue("")] 35 public string ComputerDomain 36 { 37 get { return ViewState["ComputerDomain"] == null ? String.Empty : (string)ViewState["ComputerDomain"] ; } 38 set { ViewState["ComputerDomain"] = value; } 39 } 40 41 /**//// <summary> 42 /// 登陆用户 43 /// </summary> 44 [Bindable(true), 45 Category("Data"),Description("图片存放目标计算机登陆用户,只在跨计算机上传时候填写"), 46 DefaultValue("")] 47 public string ComputerUsername 48 { 49 get { return ViewState["ComputerUsername"] == null ? String.Empty : (string)ViewState["ComputerUsername"] ; } 50 set { ViewState["ComputerUsername"] = value; } 51 } 52 53 /**//// <summary> 54 /// 登陆密码 55 /// </summary> 56 [Bindable(true), 57 Category("Data"),Description("图片存放目标计算机登陆密码,只在跨计算机上传时候填写"), 58 DefaultValue("")] 59 public string ComputerPassword 60 { 61 get { return ViewState["ComputerPassword"] == null ? String.Empty : (string)ViewState["ComputerPassword"] ; } 62 set { ViewState["ComputerPassword"] = value; } 63 } 64 65 /**//// <summary> 66 /// 文件存放路径 67 /// </summary> 68 [Bindable(true), 69 Category("Data"),Description(@"文件存放的物理路径。如果跨计算机上传,则必须填写,且包含完整共享目录路径,且保证该目录Windows权限可写,如 \\192.168.3.1\nowind\upload\;如果上传本地机器,则为图片存放物理目录全路径,如 D:\nowind\113\ ,也可以不填写,自动采用 ComputerUrlPath 指定的目录"), 70 DefaultValue("")] 71 public string ComputerFilePath 72 { 73 get { return ViewState["ComputerFilePath"] == null ? "" : (string)ViewState["ComputerFilePath"] ; } 74 set { ViewState["ComputerFilePath"] = value; } 75 } 76 77 /**//// <summary> 78 /// 文件服务路径 79 /// </summary> 80 [Bindable(true), 81 Category("Data"),Description(@"文件的Web访问路径。跨计算机上传时,必须填写Url完全路径,如 http://192.168.3.1/nowind/upload/ ;如果上传本地机器,则填写站点根目录后的全路径,如upload/file/"), 82 DefaultValue("")] 83 public string ComputerUrlPath 84 { 85 get { return ViewState["ComputerUrlPath"] == null ? String.Empty : (string)ViewState["ComputerUrlPath"] ; } 86 set 87 { 88 value = value.EndsWith(@"/") ? value : value+"/"; 89 ViewState["ComputerUrlPath"] = value; 90 } 91 } 92 #endregion 93 94 /**//// <summary> 95 /// 上传成功后是否显示文件信息 96 /// </summary> 97 [Bindable(true), 98 Category("Appearance"),Description("上传成功后是否显示文件信息"), 99 DefaultValue("")] 100 public System.Boolean IsShowFileInfo101 { 102 get { return ViewState["IsShowFileInfo"] == null ? false : (bool)ViewState["IsShowFileInfo"] ; }103 set { ViewState["IsShowFileInfo"] = value; }104 }105106 /**//// <summary>107 /// 文件大小上限108 /// </summary>109 [Bindable(true), 110 Category("Data"),Description("文件大小上限,以K为单位,默认为100K,0表示不限制"),111 DefaultValue("")] 112 public System.Int64 FileMaxSize113 { 114 get { return ViewState["FileMaxSize"] == null ? 100 : (System.Int64)ViewState["FileMaxSize"] ; }115 set 116 { 117 if( value < 0 || value > System.Int64.MaxValue)118 throw new ArgumentException("设置的值超过有效范围");119 ViewState["FileMaxSize"] = value; 120 }121 }122123 /**//// <summary>124 /// 是否覆盖服务器上已存在的同名文件125 /// </summary>126 [Bindable(true), 127 Category("Data"),Description("是否覆盖服务器上已存在的同名文件"),128 DefaultValue("")] 129 public System.Boolean IsOverwrite130 { 131 get { return ViewState["IsOverwrite"] == null ? true : (bool)ViewState["IsOverwrite"] ; }132 set { ViewState["IsOverwrite"] = value; }133 }134135 /**//// <summary>136 /// 是否重新命名上传文件137 /// </summary>138 [Bindable(true), 139 Category("Data"),Description("是否重新命名上传文件"),140 DefaultValue("")] 141 public System.Boolean IsRename142 { 143 get { return ViewState["IsRename"] == null ? true : (bool)ViewState["IsRename"] ; }144 set { ViewState["IsRename"] = value; }145 }146147 /**//// <summary>148 /// 文件类型149 /// </summary>150 [Bindable(true), 151 Category("Data"),Description("文件类型,多种文件类型以(,)分割,默认为rar,zip,doc,txt,wma,mp3,pdf类型"),152 DefaultValue("")] 153 public System.String FileType154 { 155 get { return ViewState["FileType"] == null ? "rar,zip,doc,txt,wma,mp3,pdf" : (string)ViewState["FileType"] ; }156 set { ViewState["FileType"] = value; }157 }158159 /**//// <summary>160 /// 文件的完整Url路径161 /// </summary>162 [Bindable(true), 163 Category("Data"),Description("文件的完整Url路径,相对于根目录,如image/xxx.jpg"),Browsable(false),164 DefaultValue("")] 165 public System.String FileFullUrl166 { 167 get { return ViewState["FileFullUrl"] == null ? String.Empty : (string)ViewState["FileFullUrl"] ; }168 set { ViewState["FileFullUrl"] = value; }169 }170 171 其他属性#region 其他属性172173 //控件宽度属性 174 [Bindable(true), 175 Category("Layout"), 176 DefaultValue("")] 177 public override Unit Width178 { 179 get{ return this.pnlFrame.Width;}180 set{ this.pnlFrame.Width = value;}181 }182183 //控件高度属性 184 [Bindable(true), 185 Category("Layout"), 186 DefaultValue("")] 187 public override Unit Height188 { 189 get{ return this.pnlFrame.Height;}190 set{ this.pnlFrame.Height = value;}191 }192193 //前景色属性 194 [Bindable(true), 195 Category("Appearance"), 196 DefaultValue("")] 197 public override Color ForeColor198 { 199 get{ return pnlFrame.ForeColor;}200 set{ this.pnlFrame.ForeColor = value;}201 }202203 //背景色属性 204 [Bindable(true), 205 Category("Appearance"), 206 DefaultValue("")] 207 public override Color BackColor208 { 209 get{ return pnlFrame.BackColor;}210 set{ this.pnlFrame.BackColor = value;}211 }212213 //按钮样式214 [Bindable(true), 215 Category("Appearance"),Description("按钮样式"),216 DefaultValue("")] 217 public string CssButton 218 { 219 get { return ViewState["CssButton"] == null ? String.Empty : (string)ViewState["CssButton"] ; }220 set { ViewState["CssButton"] = value; }221 }222223 //浏览框样式属性224 [Bindable(true), 225 Category("Appearance"),Description("浏览框样式属性"),226 DefaultValue("")] 227 public string CssInputFile228 { 229 get { return ViewState["CssInputFile"] == null ? String.Empty : (string)ViewState["CssInputFile"] ; }230 set { ViewState["CssInputFile"] = value; }231 }232233 //文字样式属性234 [Bindable(true), 235 Category("Appearance"),Description("文字样式属性"),236 DefaultValue("")] 237 public override string CssClass 238 { 239 get { return ViewState["CssClass"] == null ? String.Empty : (string)ViewState["CssClass"] ; }240 set { ViewState["CssClass"] = value; }241 }242243 //控件边框颜色属性 244 [Bindable(true), 245 Category("Appearance"), 246 DefaultValue("")] 247 public override Color BorderColor248 { 249 get{ return this.pnlFrame.BorderColor;}250 set{ this.pnlFrame.BorderColor = value;}251 }252253 //控件边框样式属性 254 [Bindable(true), 255 Category("Appearance"), 256 DefaultValue("")] 257 public override BorderStyle BorderStyle258 { 259 get{ return this.pnlFrame.BorderStyle;}260 set{ this.pnlFrame.BorderStyle = value;}261 }262263 //控件边框宽度属性 264 [Bindable(true), 265 Category("Appearance"), 266 DefaultValue("")] 267 public override Unit BorderWidth268 { 269 get{ return this.pnlFrame.BorderWidth;}270 set{ this.pnlFrame.BorderWidth = value;}271 }272273 #endregion274275 //处理上传成功后用户自定义事件276 [Bindable(true), 277 Category("Action"), Description("处理上传成功后用户自定义事件"),278 DefaultValue("")] 279 public event EventHandler Uploaded280 { 281 add{ this.uploaded += value;}282 remove{ this.uploaded -= value;}283 }284 #endregion285286 声明子控件#region 声明子控件287 private Label lblInfo = new Label(); //用于文件信息288 private Label lblMsg = new Label(); //上传文件重命名称289 private System.Web.UI.WebControls.FileUpload fileUpload = new FileUpload(); //浏览本地文件290 private System.Web.UI.HtmlControls.HtmlButton btnUpload = new HtmlButton(); //上传按钮291 private Panel pnlFrame = new Panel(); //承载其它控件的容器Panel控件292 #endregion293294 构造函数初始化子控件#region 构造函数初始化子控件295 public WebUploadFile()296 { 297 this.fileUpload.ID = "fileUpload";298299 this.lblInfo.ID = "lblInfo";300 this.lblInfo.Text = this.FileFullUrl;301 this.lblInfo.Visible = false;302303 this.lblMsg.ID = "lblMsg";304 this.lblMsg.Text = "";305 this.lblMsg.ForeColor = Color.Red;306 this.lblMsg.Visible = false;307308 this.btnUpload.ID = "btnUpload";309 this.btnUpload.InnerText = "上传";310 this.btnUpload.ServerClick += new EventHandler(this.Upload_Click);311312 this.pnlFrame.ForeColor = this.ForeColor;313 this.pnlFrame.BackColor = Color.Empty;314315 //将子控件添加到此自定义控件中316 this.Controls.Add(fileUpload);317 this.Controls.Add(lblInfo);318 this.Controls.Add(lblMsg);319 this.Controls.Add(btnUpload);320 this.Controls.Add(pnlFrame);321 }322323 #endregion324325 创建子控件#region 创建子控件326 protected override void EnsureChildControls()327 { 328 329 }330 #endregion331 332 将此控件呈现给指定的输出参数#region 将此控件呈现给指定的输出参数333 /**//// <summary> 334 /// 将此控件呈现给指定的输出参数。335 /// </summary>336 /// <param name="output"> 要写出到的 HTML 编写器 </param>337 protected override void Render(HtmlTextWriter output)338 { 339 //开始输出340 output.AddAttribute(HtmlTextWriterAttribute.Id,base.ID);341 this.pnlFrame.RenderBeginTag(output);342343 //在Panel中绘制表格344 output.AddAttribute(HtmlTextWriterAttribute.Border,"0");345 output.AddAttribute(HtmlTextWriterAttribute.Cellpadding,"0");346 output.AddAttribute(HtmlTextWriterAttribute.Cellspacing,"0");347 output.AddAttribute(System.Web.UI.HtmlTextWriterAttribute.Width,"100%");348 //output.AddAttribute(System.Web.UI.HtmlTextWriterAttribute.Height,"25px");349350 output.RenderBeginTag(HtmlTextWriterTag.Table); 351352 output.RenderBeginTag(HtmlTextWriterTag.Tr);353 output.AddAttribute(System.Web.UI.HtmlTextWriterAttribute.Align,"Left"); 354 //output.AddAttribute(System.Web.UI.HtmlTextWriterAttribute.Width,"70%");355 output.RenderBeginTag(HtmlTextWriterTag.Td);356 357 //文件浏览框358 //output.Write("<input name=\"" + base.ID + ":fileUpload\" id=\"" + base.ID + "_fileUpload\" class=\"" + this.CssInputFile + "\" style=\"width:75%\" type=\"file\" />");359 this.fileUpload.Attributes.Add("Width", "70%");360 this.fileUpload.Attributes.Add("Class", this.CssInputFile);361 this.fileUpload.RenderControl(output);362 output.Write(" ");363 //上传按钮364 //this.btnUpload.Attributes.Add("OnClick","javascript:if(document.getElementById('"+this.ID+"_fileUpload').value==''){alert('请浏览上传的文件');return false;}");365 this.btnUpload.Attributes.Add("Class", this.CssButton);366 this.btnUpload.CausesValidation = false;367 this.btnUpload.RenderControl(output);368369 output.Write(" ");370 //上传结果信息371 this.lblMsg.RenderControl(output);372 output.RenderEndTag();373 output.RenderEndTag();374375 //显示文件信息376 if( this.IsShowFileInfo == true )377 { 378 output.RenderBeginTag(HtmlTextWriterTag.Tr);379 output.AddAttribute(System.Web.UI.HtmlTextWriterAttribute.Valign,"Middle");380 output.AddAttribute(System.Web.UI.HtmlTextWriterAttribute.Height,"24px");381 output.AddAttribute(System.Web.UI.HtmlTextWriterAttribute.Class,this.CssClass);382 output.RenderBeginTag(HtmlTextWriterTag.Td);383 output.AddAttribute(System.Web.UI.HtmlTextWriterAttribute.Align,"left");384 output.AddAttribute(System.Web.UI.HtmlTextWriterAttribute.Valign,"absmiddle");385386 this.lblInfo.RenderControl(output);387388 output.RenderEndTag();// </td>389 output.RenderEndTag();// </tr>390 }391392 output.RenderEndTag();// </table>393 394 //结束输出395 this.pnlFrame.RenderEndTag(output);396 }397 #endregion 398399 上载文件#region 上载文件400 private void Upload_Click(object sender, System.EventArgs e)401 { 402 this.lblInfo.Visible = false;403 //this.lblInfo.Text = "";404 this.lblMsg.Visible = false;405 this.lblMsg.Text = "";406407 System.Web.UI.ClientScriptManager client = this.Page.ClientScript;408 Type cstype = Page.GetType();409410 //站点根路径411 string appPath = FileClass.GetApplicationPath();412413 // 判断路径414 if( this.fileUpload.PostedFile == null || this.fileUpload.PostedFile.ToString() == "" )415 { 416 //this.lblMsg.Text = "未发现操作文件";417 //this.lblMsg.Visible = true;418 client.RegisterStartupScript(cstype, "error", "<script language='javascript'>alert('未发现操作文件')</script>");419 return;420 }421422 FileClass classValidUser = new FileClass();423 if( this.ComputerDomain != "" ) //如果计算机地址设置不为空则默认为存放文件到远程计算机424 { 425 bool loginResult = false; //登陆远程计算机成功与否426 loginResult = classValidUser.ImpersonateValidUser(this.ComputerUsername , this.ComputerPassword , this.ComputerDomain );427 if( loginResult == false )428 { 429 //lblMsg.Visible = true;430 //lblMsg.Text = "登陆远程服务器失败";431 client.RegisterStartupScript(cstype, "error", "<script language='javascript'>alert('登陆远程服务器失败')</script>");432 return;433 }434 }435436 try437 { 438 string fileName = null; //保存的文件短名称439 HttpPostedFile filImage = this.fileUpload.PostedFile;440 string sourceFileName = null; //原始文件名称 441 sourceFileName= System.IO.Path.GetFileName(filImage.FileName);442 string sourceFileExtension = System.IO.Path.GetExtension(sourceFileName).ToLower();//扩展名 如.jpg443444 StringCollection sc = new StringCollection();445 foreach( string str in this.FileType.Split(',') )446 sc.Add( "."+str.ToLower() );447 if( !sc.Contains(sourceFileExtension) )448 { 449 client.RegisterStartupScript(cstype, "error", "<script language='javascript'>alert('文件格式不对')</script>");450 return;451 }452453 // 文件大小454 int fileLen = filImage.ContentLength; 455 if( this.FileMaxSize != 0 ) //为0则不限制上传文件大小456 { 457 // 判断文件大小458 if(fileLen < 0 || fileLen > this.FileMaxSize * 1024)459 { 460 string msg = "文件大小不能超过"+this.FileMaxSize+"K";461 client.RegisterStartupScript(cstype, "error", "<script language='javascript'>alert('" + msg + "')</script>");462 return;463 }464 }465466 // 读取文件到缓存467 byte[] bufData = new byte[fileLen];468 filImage.InputStream.Read(bufData, 0, fileLen);469 MemoryStream ms = new MemoryStream(bufData);470 if( this.IsRename )471 { 472 // 以时间命名文件名,精确到毫秒473 DateTime dtNow = DateTime.Now;474 fileName = dtNow.ToString("yyyyMMddhhmmss")+DateTime.Now.Millisecond.ToString("000")+sourceFileExtension;475 }476 else477 fileName = sourceFileName;478479 // 文件存放路径文件夹480 string filePath = "";481 if(this.ComputerFilePath == null || this.ComputerFilePath == "" )482 { 483 filePath = appPath + this.ComputerUrlPath;484 filePath = filePath.EndsWith(@"/") ? filePath : filePath+"/";485 filePath = filePath.Replace(@"//",@"/");486 filePath = this.Page.Server.MapPath( filePath );487 }488 else489 filePath = this.ComputerFilePath.Replace(@"/",@"\");490 filePath = filePath.EndsWith(@"\") == true ? filePath : filePath + @"\";491 string fileFullPath = filePath + fileName;492493 //返回文件url全路径,以"/"结尾494 string fileUrlPath = this.ComputerUrlPath.Replace(@"\",@"/");495 fileUrlPath = this.ComputerUrlPath.EndsWith(@"/") == true ? this.ComputerUrlPath : this.ComputerUrlPath + @"/";496 fileUrlPath += fileName;497498 // 判断存放图片文件的目录是否存在,如果不存在,则创建。499 DirectoryInfo di = new DirectoryInfo(filePath);500 if( di.Attributes == FileAttributes.ReadOnly )501 { 502 string msg = "指定文件夹为只读,不能写入文件";503 client.RegisterStartupScript(cstype, "error", "<script language='javascript'>alert('" + msg + "')</script>");504 return;505 }506 if(!Directory.Exists(filePath))507 Directory.CreateDirectory(filePath);508 if( File.Exists( fileFullPath ) && !this.IsOverwrite )509 { 510 string msg = "文件已经存在";511 client.RegisterStartupScript(cstype, "error", "<script language='javascript'>alert('" + msg + "')</script>");512 return;513 }514515 // 把文件写入服务器516 FileStream newFile = new FileStream(fileFullPath,FileMode.Create);517 newFile.Write(bufData,0,fileLen);518 newFile.Flush();519 newFile.Close();520521 // 注销远程登陆522 if( this.ComputerDomain != "" )523 classValidUser.UndoImpersonation();524525 //返回文件路径526 this.FileFullUrl = fileUrlPath;527 528 //保存路径信息529 lblMsg.Visible=true;530 lblMsg.Text="上载成功";531 lblInfo.Visible = true;532 double size = (double)fileLen/1024;533 lblInfo.Text = "文件名:"+fileName+" 文件大小:"+size.ToString("0.00")+"K";534535 //激发用户自定义事件536 if( uploaded != null )537 uploaded(this,new System.EventArgs());538539 } 540 catch(Exception ex)541 { 542 lblMsg.Visible=true;543 lblMsg.Text="上载失败:"+ex.Message;544 lblInfo.Visible = false;545 }546 }547 #endregion548549 }550}
上传图片是经常会使用到的问题,不过每次都去些那些相同的代码确实够麻烦,所有就有了下面这个东东的出现了,哈哈!照顾到大多数人不同的需求,所以提供了多种自定义的功能,不急,下面一一介绍:
1、用户可控制是否生成缩略图。
2、用户自己定义缩略图大小,可以指定具体px或%,可以同时指定宽和高,也可以只指定宽,如果只指定宽的参数,则缩略图高度会按原始图片的宽/高比例计算得到。 3、可自定义是否为图片加上水印,水印有两种方式,一种是文本,一种是图片,分别可自定义。并且水印的位置可控制。如果是文本水印,可指定绘制的文字、文字的大小、颜色和阴影颜色已经阴影的偏移距离。 4、可控制图片上传后是否立即显示,显示位置(上传框上方或下方),显示的信息有三种可选:图片和图片信息、图片信息、仅图片。 5、可控制图片的文件大小、图片的绝对尺寸大小。 6、自定义图片存放路径。 7、可将图片上传至远程服务器,也就是非web程序运行的其他计算机,条件是需要设置相关的远程服务器登陆的ip或机器名、登陆帐号、登陆密码、共享路径和用于图片web访问Url路径,以便存放数据库。 8、用户自己定义文件浏览框、按钮的样式。
9、另外拥护上传成功后会返回两个属性 UrlInfoBigImage和UrlInfoSmallImage ,分别是大小图片的url路径,直接获取就可以了。
10、对于控件的设置,如果是新上传图片,只需要设置上传路径ComputerUrlPath属性,如果是编辑已经上传的图片,只需要对UrlInfoBigImage赋值即可。 11、支持上传后事件,方便开发人员定义不同操作。 12、所有的路径为相对站点根路径,比如站点为 ,其中nowind为虚拟目录,则图片的UrlInfoBigImage应该为 images/head/1.jpg 注意前面不带"/"。则ComputerUrlPath应该为 images/head/