自定义服务器控件开发之2:文件上传控件
文件上传的控件,支持上传后事件,跨服务器上传,自定义可上传文件类型、大小,以及上传文件命名规则。
文件上传的控件,支持上传后事件,跨服务器上传,自定义可上传文件类型、大小,以及上传文件命名规则。
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 IsShowFileInfo
101
{
102
get
{ return ViewState["IsShowFileInfo"] == null ? false : (bool)ViewState["IsShowFileInfo"] ; }
103
set
{ ViewState["IsShowFileInfo"] = value; }
104
}
105
106
/**//// <summary>
107
/// 文件大小上限
108
/// </summary>
109
[Bindable(true),
110
Category("Data"),Description("文件大小上限,以K为单位,默认为100K,0表示不限制"),
111
DefaultValue("")]
112
public System.Int64 FileMaxSize
113
{
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
}
122
123
/**//// <summary>
124
/// 是否覆盖服务器上已存在的同名文件
125
/// </summary>
126
[Bindable(true),
127
Category("Data"),Description("是否覆盖服务器上已存在的同名文件"),
128
DefaultValue("")]
129
public System.Boolean IsOverwrite
130
{
131
get
{ return ViewState["IsOverwrite"] == null ? true : (bool)ViewState["IsOverwrite"] ; }
132
set
{ ViewState["IsOverwrite"] = value; }
133
}
134
135
/**//// <summary>
136
/// 是否重新命名上传文件
137
/// </summary>
138
[Bindable(true),
139
Category("Data"),Description("是否重新命名上传文件"),
140
DefaultValue("")]
141
public System.Boolean IsRename
142
{
143
get
{ return ViewState["IsRename"] == null ? true : (bool)ViewState["IsRename"] ; }
144
set
{ ViewState["IsRename"] = value; }
145
}
146
147
/**//// <summary>
148
/// 文件类型
149
/// </summary>
150
[Bindable(true),
151
Category("Data"),Description("文件类型,多种文件类型以(,)分割,默认为rar,zip,doc,txt,wma,mp3,pdf类型"),
152
DefaultValue("")]
153
public System.String FileType
154
{
155
get
{ return ViewState["FileType"] == null ? "rar,zip,doc,txt,wma,mp3,pdf" : (string)ViewState["FileType"] ; }
156
set
{ ViewState["FileType"] = value; }
157
}
158
159
/**//// <summary>
160
/// 文件的完整Url路径
161
/// </summary>
162
[Bindable(true),
163
Category("Data"),Description("文件的完整Url路径,相对于根目录,如image/xxx.jpg"),Browsable(false),
164
DefaultValue("")]
165
public System.String FileFullUrl
166
{
167
get
{ return ViewState["FileFullUrl"] == null ? String.Empty : (string)ViewState["FileFullUrl"] ; }
168
set
{ ViewState["FileFullUrl"] = value; }
169
}
170
171
其他属性#region 其他属性
172
173
//控件宽度属性
174
[Bindable(true),
175
Category("Layout"),
176
DefaultValue("")]
177
public override Unit Width
178
{
179
get
{ return this.pnlFrame.Width;}
180
set
{ this.pnlFrame.Width = value;}
181
}
182
183
//控件高度属性
184
[Bindable(true),
185
Category("Layout"),
186
DefaultValue("")]
187
public override Unit Height
188
{
189
get
{ return this.pnlFrame.Height;}
190
set
{ this.pnlFrame.Height = value;}
191
}
192
193
//前景色属性
194
[Bindable(true),
195
Category("Appearance"),
196
DefaultValue("")]
197
public override Color ForeColor
198
{
199
get
{ return pnlFrame.ForeColor;}
200
set
{ this.pnlFrame.ForeColor = value;}
201
}
202
203
//背景色属性
204
[Bindable(true),
205
Category("Appearance"),
206
DefaultValue("")]
207
public override Color BackColor
208
{
209
get
{ return pnlFrame.BackColor;}
210
set
{ this.pnlFrame.BackColor = value;}
211
}
212
213
//按钮样式
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
}
222
223
//浏览框样式属性
224
[Bindable(true),
225
Category("Appearance"),Description("浏览框样式属性"),
226
DefaultValue("")]
227
public string CssInputFile
228
{
229
get
{ return ViewState["CssInputFile"] == null ? String.Empty : (string)ViewState["CssInputFile"] ; }
230
set
{ ViewState["CssInputFile"] = value; }
231
}
232
233
//文字样式属性
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
}
242
243
//控件边框颜色属性
244
[Bindable(true),
245
Category("Appearance"),
246
DefaultValue("")]
247
public override Color BorderColor
248
{
249
get
{ return this.pnlFrame.BorderColor;}
250
set
{ this.pnlFrame.BorderColor = value;}
251
}
252
253
//控件边框样式属性
254
[Bindable(true),
255
Category("Appearance"),
256
DefaultValue("")]
257
public override BorderStyle BorderStyle
258
{
259
get
{ return this.pnlFrame.BorderStyle;}
260
set
{ this.pnlFrame.BorderStyle = value;}
261
}
262
263
//控件边框宽度属性
264
[Bindable(true),
265
Category("Appearance"),
266
DefaultValue("")]
267
public override Unit BorderWidth
268
{
269
get
{ return this.pnlFrame.BorderWidth;}
270
set
{ this.pnlFrame.BorderWidth = value;}
271
}
272
273
#endregion
274
275
//处理上传成功后用户自定义事件
276
[Bindable(true),
277
Category("Action"), Description("处理上传成功后用户自定义事件"),
278
DefaultValue("")]
279
public event EventHandler Uploaded
280
{
281
add
{ this.uploaded += value;}
282
remove
{ this.uploaded -= value;}
283
}
284
#endregion
285
286
声明子控件#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
#endregion
293
294
构造函数初始化子控件#region 构造函数初始化子控件
295
public WebUploadFile()
296
{
297
this.fileUpload.ID = "fileUpload";
298
299
this.lblInfo.ID = "lblInfo";
300
this.lblInfo.Text = this.FileFullUrl;
301
this.lblInfo.Visible = false;
302
303
this.lblMsg.ID = "lblMsg";
304
this.lblMsg.Text = "";
305
this.lblMsg.ForeColor = Color.Red;
306
this.lblMsg.Visible = false;
307
308
this.btnUpload.ID = "btnUpload";
309
this.btnUpload.InnerText = "上传";
310
this.btnUpload.ServerClick += new EventHandler(this.Upload_Click);
311
312
this.pnlFrame.ForeColor = this.ForeColor;
313
this.pnlFrame.BackColor = Color.Empty;
314
315
//将子控件添加到此自定义控件中
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
}
322
323
#endregion
324
325
创建子控件#region 创建子控件
326
protected override void EnsureChildControls()
327
{
328
329
}
330
#endregion
331
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);
342
343
//在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");
349
350
output.RenderBeginTag(HtmlTextWriterTag.Table);
351
352
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);
368
369
output.Write(" ");
370
//上传结果信息
371
this.lblMsg.RenderControl(output);
372
output.RenderEndTag();
373
output.RenderEndTag();
374
375
//显示文件信息
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");
385
386
this.lblInfo.RenderControl(output);
387
388
output.RenderEndTag();// </td>
389
output.RenderEndTag();// </tr>
390
}
391
392
output.RenderEndTag();// </table>
393
394
//结束输出
395
this.pnlFrame.RenderEndTag(output);
396
}
397
#endregion
398
399
上载文件#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 = "";
406
407
System.Web.UI.ClientScriptManager client = this.Page.ClientScript;
408
Type cstype = Page.GetType();
409
410
//站点根路径
411
string appPath = FileClass.GetApplicationPath();
412
413
// 判断路径
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
}
421
422
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
}
435
436
try
437
{
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();//扩展名 如.jpg
443
444
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
}
452
453
// 文件大小
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
}
465
466
// 读取文件到缓存
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
else
477
fileName = sourceFileName;
478
479
// 文件存放路径文件夹
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
else
489
filePath = this.ComputerFilePath.Replace(@"/",@"\");
490
filePath = filePath.EndsWith(@"\") == true ? filePath : filePath + @"\";
491
string fileFullPath = filePath + fileName;
492
493
//返回文件url全路径,以"/"结尾
494
string fileUrlPath = this.ComputerUrlPath.Replace(@"\",@"/");
495
fileUrlPath = this.ComputerUrlPath.EndsWith(@"/") == true ? this.ComputerUrlPath : this.ComputerUrlPath + @"/";
496
fileUrlPath += fileName;
497
498
// 判断存放图片文件的目录是否存在,如果不存在,则创建。
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
}
514
515
// 把文件写入服务器
516
FileStream newFile = new FileStream(fileFullPath,FileMode.Create);
517
newFile.Write(bufData,0,fileLen);
518
newFile.Flush();
519
newFile.Close();
520
521
// 注销远程登陆
522
if( this.ComputerDomain != "" )
523
classValidUser.UndoImpersonation();
524
525
//返回文件路径
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";
534
535
//激发用户自定义事件
536
if( uploaded != null )
537
uploaded(this,new System.EventArgs());
538
539
}
540
catch(Exception ex)
541
{
542
lblMsg.Visible=true;
543
lblMsg.Text="上载失败:"+ex.Message;
544
lblInfo.Visible = false;
545
}
546
}
547
#endregion
548
549
}
550
}
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.WebCtrlLib12


{13

/**//// <summary>14
/// 文件上传控件15
/// Author: nowind16
/// Date: 2006-3-417
/// Email: hgh113@sina.com18
/// QQ: 8750595919
/// </summary>20
[DefaultProperty("Text"), 21
ToolboxData("<{0}:WebUploadFile runat=server></{0}:WebUploadFile>")]22
public class WebUploadFile : System.Web.UI.WebControls.WebControl,INamingContainer23

{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 ComputerDomain36

{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 ComputerUsername48

{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 ComputerPassword60

{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 ComputerFilePath72

{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 ComputerUrlPath84

{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
#endregion93

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
}105

106

/**//// <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
}122

123

/**//// <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
}134

135

/**//// <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
}146

147

/**//// <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
}158

159

/**//// <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 其他属性172

173
//控件宽度属性 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
}182

183
//控件高度属性 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
}192

193
//前景色属性 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
}202

203
//背景色属性 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
}212

213
//按钮样式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
}222

223
//浏览框样式属性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
}232

233
//文字样式属性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
}242

243
//控件边框颜色属性 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
}252

253
//控件边框样式属性 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
}262

263
//控件边框宽度属性 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
}272

273
#endregion274

275
//处理上传成功后用户自定义事件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
#endregion285

286

声明子控件#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
#endregion293

294

构造函数初始化子控件#region 构造函数初始化子控件295
public WebUploadFile()296

{297
this.fileUpload.ID = "fileUpload";298

299
this.lblInfo.ID = "lblInfo";300
this.lblInfo.Text = this.FileFullUrl;301
this.lblInfo.Visible = false;302

303
this.lblMsg.ID = "lblMsg";304
this.lblMsg.Text = "";305
this.lblMsg.ForeColor = Color.Red;306
this.lblMsg.Visible = false;307

308
this.btnUpload.ID = "btnUpload";309
this.btnUpload.InnerText = "上传";310
this.btnUpload.ServerClick += new EventHandler(this.Upload_Click);311

312
this.pnlFrame.ForeColor = this.ForeColor;313
this.pnlFrame.BackColor = Color.Empty;314

315
//将子控件添加到此自定义控件中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
}322

323
#endregion324

325

创建子控件#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);342

343
//在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");349

350
output.RenderBeginTag(HtmlTextWriterTag.Table); 351

352
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);368

369
output.Write(" ");370
//上传结果信息371
this.lblMsg.RenderControl(output);372
output.RenderEndTag();373
output.RenderEndTag();374

375
//显示文件信息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");385

386
this.lblInfo.RenderControl(output);387

388
output.RenderEndTag();// </td>389
output.RenderEndTag();// </tr>390
}391

392
output.RenderEndTag();// </table>393
394
//结束输出395
this.pnlFrame.RenderEndTag(output);396
}397
#endregion 398

399

上载文件#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 = "";406

407
System.Web.UI.ClientScriptManager client = this.Page.ClientScript;408
Type cstype = Page.GetType();409

410
//站点根路径411
string appPath = FileClass.GetApplicationPath();412

413
// 判断路径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
}421

422
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
}435

436
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();//扩展名 如.jpg443

444
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
}452

453
// 文件大小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
}465

466
// 读取文件到缓存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;478

479
// 文件存放路径文件夹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;492

493
//返回文件url全路径,以"/"结尾494
string fileUrlPath = this.ComputerUrlPath.Replace(@"\",@"/");495
fileUrlPath = this.ComputerUrlPath.EndsWith(@"/") == true ? this.ComputerUrlPath : this.ComputerUrlPath + @"/";496
fileUrlPath += fileName;497

498
// 判断存放图片文件的目录是否存在,如果不存在,则创建。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
}514

515
// 把文件写入服务器516
FileStream newFile = new FileStream(fileFullPath,FileMode.Create);517
newFile.Write(bufData,0,fileLen);518
newFile.Flush();519
newFile.Close();520

521
// 注销远程登陆522
if( this.ComputerDomain != "" )523
classValidUser.UndoImpersonation();524

525
//返回文件路径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";534

535
//激发用户自定义事件536
if( uploaded != null )537
uploaded(this,new System.EventArgs());538

539
} 540
catch(Exception ex)541

{542
lblMsg.Visible=true;543
lblMsg.Text="上载失败:"+ex.Message;544
lblInfo.Visible = false;545
}546
}547
#endregion548

549
}550
}
浙公网安备 33010602011771号