自定义服务器控件开发之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 ExpandedBlockStart.gifContractedBlock.gif {
 13ExpandedSubBlockStart.gifContractedSubBlock.gif    /**//// <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
 23ExpandedSubBlockStart.gifContractedSubBlock.gif    {
 24        private event EventHandler uploaded;
 25        
 26ContractedSubBlock.gifExpandedSubBlockStart.gif        属性#region 属性
 27
 28ContractedSubBlock.gifExpandedSubBlockStart.gif        机器属性#region 机器属性
 29ExpandedSubBlockStart.gifContractedSubBlock.gif        /**//// <summary>
 30        /// 域
 31        /// </summary>

 32        [Bindable(true), 
 33        Category("Data"),Description("图片存放目标计算机的IP或者机器名,只在跨计算机上传时候填写"),
 34        DefaultValue("")] 
 35        public string ComputerDomain
 36ExpandedSubBlockStart.gifContractedSubBlock.gif        {
 37ExpandedSubBlockStart.gifContractedSubBlock.gif            get return ViewState["ComputerDomain"== null ? String.Empty : (string)ViewState["ComputerDomain"] ; }
 38ExpandedSubBlockStart.gifContractedSubBlock.gif            set { ViewState["ComputerDomain"= value; }
 39        }

 40
 41ExpandedSubBlockStart.gifContractedSubBlock.gif        /**//// <summary>
 42        /// 登陆用户
 43        /// </summary>

 44        [Bindable(true), 
 45        Category("Data"),Description("图片存放目标计算机登陆用户,只在跨计算机上传时候填写"),
 46        DefaultValue("")] 
 47        public string ComputerUsername
 48ExpandedSubBlockStart.gifContractedSubBlock.gif        {
 49ExpandedSubBlockStart.gifContractedSubBlock.gif            get return ViewState["ComputerUsername"== null ? String.Empty : (string)ViewState["ComputerUsername"] ; }
 50ExpandedSubBlockStart.gifContractedSubBlock.gif            set { ViewState["ComputerUsername"= value; }
 51        }

 52
 53ExpandedSubBlockStart.gifContractedSubBlock.gif        /**//// <summary>
 54        /// 登陆密码
 55        /// </summary>

 56        [Bindable(true), 
 57        Category("Data"),Description("图片存放目标计算机登陆密码,只在跨计算机上传时候填写"),
 58        DefaultValue("")] 
 59        public string ComputerPassword
 60ExpandedSubBlockStart.gifContractedSubBlock.gif        {
 61ExpandedSubBlockStart.gifContractedSubBlock.gif            get return ViewState["ComputerPassword"== null ? String.Empty : (string)ViewState["ComputerPassword"] ; }
 62ExpandedSubBlockStart.gifContractedSubBlock.gif            set { ViewState["ComputerPassword"= value; }
 63        }

 64
 65ExpandedSubBlockStart.gifContractedSubBlock.gif        /**//// <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
 72ExpandedSubBlockStart.gifContractedSubBlock.gif        {
 73ExpandedSubBlockStart.gifContractedSubBlock.gif            get return ViewState["ComputerFilePath"== null ? "" : (string)ViewState["ComputerFilePath"] ; }
 74ExpandedSubBlockStart.gifContractedSubBlock.gif            set { ViewState["ComputerFilePath"= value;  }
 75        }

 76
 77ExpandedSubBlockStart.gifContractedSubBlock.gif        /**//// <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
 84ExpandedSubBlockStart.gifContractedSubBlock.gif        {
 85ExpandedSubBlockStart.gifContractedSubBlock.gif            get return ViewState["ComputerUrlPath"== null ? String.Empty : (string)ViewState["ComputerUrlPath"] ; }
 86            set 
 87ExpandedSubBlockStart.gifContractedSubBlock.gif            {
 88                value = value.EndsWith(@"/"? value : value+"/";
 89                ViewState["ComputerUrlPath"= value; 
 90            }

 91        }

 92        #endregion

 93
 94ExpandedSubBlockStart.gifContractedSubBlock.gif        /**//// <summary>
 95        /// 上传成功后是否显示文件信息
 96        /// </summary>

 97        [Bindable(true), 
 98        Category("Appearance"),Description("上传成功后是否显示文件信息"),
 99        DefaultValue("")] 
100        public System.Boolean IsShowFileInfo
101ExpandedSubBlockStart.gifContractedSubBlock.gif        {
102ExpandedSubBlockStart.gifContractedSubBlock.gif            get return ViewState["IsShowFileInfo"== null ? false : (bool)ViewState["IsShowFileInfo"] ; }
103ExpandedSubBlockStart.gifContractedSubBlock.gif            set { ViewState["IsShowFileInfo"= value; }
104        }

105
106ExpandedSubBlockStart.gifContractedSubBlock.gif        /**//// <summary>
107        /// 文件大小上限
108        /// </summary>

109        [Bindable(true), 
110        Category("Data"),Description("文件大小上限,以K为单位,默认为100K,0表示不限制"),
111        DefaultValue("")] 
112        public System.Int64 FileMaxSize
113ExpandedSubBlockStart.gifContractedSubBlock.gif        {
114ExpandedSubBlockStart.gifContractedSubBlock.gif            get return ViewState["FileMaxSize"== null ? 100 : (System.Int64)ViewState["FileMaxSize"] ; }
115            set 
116ExpandedSubBlockStart.gifContractedSubBlock.gif            
117                if( value < 0 || value > System.Int64.MaxValue)
118                    throw new ArgumentException("设置的值超过有效范围");
119                ViewState["FileMaxSize"= value; 
120            }

121        }

122
123ExpandedSubBlockStart.gifContractedSubBlock.gif        /**//// <summary>
124        /// 是否覆盖服务器上已存在的同名文件
125        /// </summary>

126        [Bindable(true), 
127        Category("Data"),Description("是否覆盖服务器上已存在的同名文件"),
128        DefaultValue("")] 
129        public System.Boolean IsOverwrite
130ExpandedSubBlockStart.gifContractedSubBlock.gif        {
131ExpandedSubBlockStart.gifContractedSubBlock.gif            get return ViewState["IsOverwrite"== null ? true : (bool)ViewState["IsOverwrite"] ; }
132ExpandedSubBlockStart.gifContractedSubBlock.gif            set { ViewState["IsOverwrite"= value; }
133        }

134
135ExpandedSubBlockStart.gifContractedSubBlock.gif        /**//// <summary>
136        /// 是否重新命名上传文件
137        /// </summary>

138        [Bindable(true), 
139        Category("Data"),Description("是否重新命名上传文件"),
140        DefaultValue("")] 
141        public System.Boolean IsRename
142ExpandedSubBlockStart.gifContractedSubBlock.gif        {
143ExpandedSubBlockStart.gifContractedSubBlock.gif            get return ViewState["IsRename"== null ? true : (bool)ViewState["IsRename"] ; }
144ExpandedSubBlockStart.gifContractedSubBlock.gif            set { ViewState["IsRename"= value; }
145        }

146
147ExpandedSubBlockStart.gifContractedSubBlock.gif        /**//// <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
154ExpandedSubBlockStart.gifContractedSubBlock.gif        {
155ExpandedSubBlockStart.gifContractedSubBlock.gif            get return ViewState["FileType"== null ? "rar,zip,doc,txt,wma,mp3,pdf" : (string)ViewState["FileType"] ; }
156ExpandedSubBlockStart.gifContractedSubBlock.gif            set { ViewState["FileType"= value; }
157        }

158
159ExpandedSubBlockStart.gifContractedSubBlock.gif        /**//// <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
166ExpandedSubBlockStart.gifContractedSubBlock.gif        {
167ExpandedSubBlockStart.gifContractedSubBlock.gif            get return ViewState["FileFullUrl"== null ? String.Empty : (string)ViewState["FileFullUrl"] ; }
168ExpandedSubBlockStart.gifContractedSubBlock.gif            set { ViewState["FileFullUrl"= value; }
169        }

170        
171ContractedSubBlock.gifExpandedSubBlockStart.gif        其他属性#region 其他属性
172
173        //控件宽度属性 
174        [Bindable(true), 
175        Category("Layout"), 
176        DefaultValue("")] 
177        public override Unit Width
178ExpandedSubBlockStart.gifContractedSubBlock.gif        {
179ExpandedSubBlockStart.gifContractedSubBlock.gif            getreturn this.pnlFrame.Width;}
180ExpandedSubBlockStart.gifContractedSubBlock.gif            setthis.pnlFrame.Width = value;}
181        }

182
183        //控件高度属性 
184        [Bindable(true), 
185        Category("Layout"), 
186        DefaultValue("")] 
187        public override Unit Height
188ExpandedSubBlockStart.gifContractedSubBlock.gif        {
189ExpandedSubBlockStart.gifContractedSubBlock.gif            getreturn this.pnlFrame.Height;}
190ExpandedSubBlockStart.gifContractedSubBlock.gif            setthis.pnlFrame.Height = value;}
191        }

192
193        //前景色属性 
194        [Bindable(true), 
195        Category("Appearance"), 
196        DefaultValue("")] 
197        public override Color ForeColor
198ExpandedSubBlockStart.gifContractedSubBlock.gif        {
199ExpandedSubBlockStart.gifContractedSubBlock.gif            getreturn pnlFrame.ForeColor;}
200ExpandedSubBlockStart.gifContractedSubBlock.gif            setthis.pnlFrame.ForeColor = value;}
201        }

202
203        //背景色属性 
204        [Bindable(true), 
205        Category("Appearance"), 
206        DefaultValue("")] 
207        public override Color BackColor
208ExpandedSubBlockStart.gifContractedSubBlock.gif        {
209ExpandedSubBlockStart.gifContractedSubBlock.gif            getreturn pnlFrame.BackColor;}
210ExpandedSubBlockStart.gifContractedSubBlock.gif            setthis.pnlFrame.BackColor = value;}
211        }

212
213        //按钮样式
214        [Bindable(true), 
215        Category("Appearance"),Description("按钮样式"),
216        DefaultValue("")] 
217        public string CssButton 
218ExpandedSubBlockStart.gifContractedSubBlock.gif        {
219ExpandedSubBlockStart.gifContractedSubBlock.gif            get return ViewState["CssButton"== null ? String.Empty : (string)ViewState["CssButton"] ; }
220ExpandedSubBlockStart.gifContractedSubBlock.gif            set { ViewState["CssButton"= value; }
221        }

222
223        //浏览框样式属性
224        [Bindable(true), 
225        Category("Appearance"),Description("浏览框样式属性"),
226        DefaultValue("")] 
227        public string CssInputFile
228ExpandedSubBlockStart.gifContractedSubBlock.gif        {
229ExpandedSubBlockStart.gifContractedSubBlock.gif            get return ViewState["CssInputFile"== null ? String.Empty : (string)ViewState["CssInputFile"] ; }
230ExpandedSubBlockStart.gifContractedSubBlock.gif            set { ViewState["CssInputFile"= value; }
231        }

232
233        //文字样式属性
234        [Bindable(true), 
235        Category("Appearance"),Description("文字样式属性"),
236        DefaultValue("")] 
237        public override string CssClass 
238ExpandedSubBlockStart.gifContractedSubBlock.gif        {
239ExpandedSubBlockStart.gifContractedSubBlock.gif            get return ViewState["CssClass"== null ? String.Empty : (string)ViewState["CssClass"] ; }
240ExpandedSubBlockStart.gifContractedSubBlock.gif            set { ViewState["CssClass"= value; }
241        }

242
243        //控件边框颜色属性 
244        [Bindable(true), 
245        Category("Appearance"), 
246        DefaultValue("")] 
247        public override Color BorderColor
248ExpandedSubBlockStart.gifContractedSubBlock.gif        {
249ExpandedSubBlockStart.gifContractedSubBlock.gif            getreturn this.pnlFrame.BorderColor;}
250ExpandedSubBlockStart.gifContractedSubBlock.gif            setthis.pnlFrame.BorderColor = value;}
251        }

252
253        //控件边框样式属性 
254        [Bindable(true), 
255        Category("Appearance"), 
256        DefaultValue("")] 
257        public override BorderStyle BorderStyle
258ExpandedSubBlockStart.gifContractedSubBlock.gif        {
259ExpandedSubBlockStart.gifContractedSubBlock.gif            getreturn this.pnlFrame.BorderStyle;}
260ExpandedSubBlockStart.gifContractedSubBlock.gif            setthis.pnlFrame.BorderStyle = value;}
261        }

262
263        //控件边框宽度属性 
264        [Bindable(true), 
265        Category("Appearance"), 
266        DefaultValue("")] 
267        public override Unit BorderWidth
268ExpandedSubBlockStart.gifContractedSubBlock.gif        {
269ExpandedSubBlockStart.gifContractedSubBlock.gif            getreturn this.pnlFrame.BorderWidth;}
270ExpandedSubBlockStart.gifContractedSubBlock.gif            setthis.pnlFrame.BorderWidth = value;}
271        }

272
273        #endregion

274
275        //处理上传成功后用户自定义事件
276        [Bindable(true), 
277        Category("Action"), Description("处理上传成功后用户自定义事件"),
278        DefaultValue("")] 
279        public event EventHandler Uploaded
280ExpandedSubBlockStart.gifContractedSubBlock.gif        {
281ExpandedSubBlockStart.gifContractedSubBlock.gif            addthis.uploaded += value;}
282ExpandedSubBlockStart.gifContractedSubBlock.gif            removethis.uploaded -= value;}
283        }

284        #endregion

285
286ContractedSubBlock.gifExpandedSubBlockStart.gif        声明子控件#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
294ContractedSubBlock.gifExpandedSubBlockStart.gif        构造函数初始化子控件#region    构造函数初始化子控件
295        public WebUploadFile()
296ExpandedSubBlockStart.gifContractedSubBlock.gif        {
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
325ContractedSubBlock.gifExpandedSubBlockStart.gif        创建子控件#region 创建子控件
326        protected override void EnsureChildControls()
327ExpandedSubBlockStart.gifContractedSubBlock.gif        {
328            
329        }

330        #endregion

331    
332ContractedSubBlock.gifExpandedSubBlockStart.gif        将此控件呈现给指定的输出参数#region 将此控件呈现给指定的输出参数
333ExpandedSubBlockStart.gifContractedSubBlock.gif        /**//// <summary> 
334        /// 将此控件呈现给指定的输出参数。
335        /// </summary>
336        /// <param name="output"> 要写出到的 HTML 编写器 </param>

337        protected override void Render(HtmlTextWriter output)
338ExpandedSubBlockStart.gifContractedSubBlock.gif        {
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("&nbsp;");
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("&nbsp;");
370            //上传结果信息
371            this.lblMsg.RenderControl(output);
372            output.RenderEndTag();
373            output.RenderEndTag();
374
375            //显示文件信息
376            ifthis.IsShowFileInfo == true )
377ExpandedSubBlockStart.gifContractedSubBlock.gif            {
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
399ContractedSubBlock.gifExpandedSubBlockStart.gif        上载文件#region 上载文件
400        private void Upload_Click(object sender, System.EventArgs e)
401ExpandedSubBlockStart.gifContractedSubBlock.gif        {
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            ifthis.fileUpload.PostedFile == null || this.fileUpload.PostedFile.ToString() == "" )
415ExpandedSubBlockStart.gifContractedSubBlock.gif            {
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            ifthis.ComputerDomain != "" )    //如果计算机地址设置不为空则默认为存放文件到远程计算机
424ExpandedSubBlockStart.gifContractedSubBlock.gif            {
425                bool loginResult = false;    //登陆远程计算机成功与否
426                loginResult = classValidUser.ImpersonateValidUser(this.ComputerUsername , this.ComputerPassword , this.ComputerDomain );
427                if( loginResult == false )
428ExpandedSubBlockStart.gifContractedSubBlock.gif                {
429                    //lblMsg.Visible = true;
430                    //lblMsg.Text = "登陆远程服务器失败";
431                    client.RegisterStartupScript(cstype, "error""<script language='javascript'>alert('登陆远程服务器失败')</script>");
432                    return;
433                }

434            }

435
436            try
437ExpandedSubBlockStart.gifContractedSubBlock.gif            {
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                foreachstring str in this.FileType.Split(',') )
446                    sc.Add( "."+str.ToLower() );
447                if!sc.Contains(sourceFileExtension) )
448ExpandedSubBlockStart.gifContractedSubBlock.gif                {
449                    client.RegisterStartupScript(cstype, "error""<script language='javascript'>alert('文件格式不对')</script>");
450                    return;
451                }

452
453                // 文件大小
454                int fileLen = filImage.ContentLength; 
455                ifthis.FileMaxSize != 0 )    //为0则不限制上传文件大小
456ExpandedSubBlockStart.gifContractedSubBlock.gif                {
457                    // 判断文件大小
458                    if(fileLen < 0 || fileLen > this.FileMaxSize * 1024)
459ExpandedSubBlockStart.gifContractedSubBlock.gif                    {
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                ifthis.IsRename )
471ExpandedSubBlockStart.gifContractedSubBlock.gif                {
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 == "" )
482ExpandedSubBlockStart.gifContractedSubBlock.gif                {
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 )
501ExpandedSubBlockStart.gifContractedSubBlock.gif                {
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 )
509ExpandedSubBlockStart.gifContractedSubBlock.gif                {
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                ifthis.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+"&nbsp;&nbsp;&nbsp;文件大小:"+size.ToString("0.00")+"K";
534
535                //激发用户自定义事件
536                if( uploaded != null )
537                    uploaded(this,new System.EventArgs());
538
539            }
                    
540            catch(Exception ex)
541ExpandedSubBlockStart.gifContractedSubBlock.gif            {
542                lblMsg.Visible=true;
543                lblMsg.Text="上载失败:"+ex.Message;
544                lblInfo.Visible = false;
545            }

546        }

547        #endregion

548
549    }

550}

自定义服务器控件开发之3:自定义缩略图和水印的图片上传控件

        上传图片是经常会使用到的问题,不过每次都去些那些相同的代码确实够麻烦,所有就有了下面这个东东的出现了,哈哈!照顾到大多数人不同的需求,所以提供了多种自定义的功能,不急,下面一一介绍:
         1、用户可控制是否生成缩略图。
         2、用户自己定义缩略图大小,可以指定具体px或%,可以同时指定宽和高,也可以只指定宽,如果只指定宽的参数,则缩略图高度会按原始图片的宽/高比例计算得到。
         3、可自定义是否为图片加上水印,水印有两种方式,一种是文本,一种是图片,分别可自定义。并且水印的位置可控制。如果是文本水印,可指定绘制的文字、文字的大小、颜色和阴影颜色已经阴影的偏移距离。
         4、可控制图片上传后是否立即显示,显示位置(上传框上方或下方),显示的信息有三种可选:图片和图片信息、图片信息、仅图片。
         5、可控制图片的文件大小、图片的绝对尺寸大小。
         6、自定义图片存放路径。
         7、可将图片上传至远程服务器,也就是非web程序运行的其他计算机,条件是需要设置相关的远程服务器登陆的ip或机器名、登陆帐号、登陆密码、共享路径和用于图片web访问Url路径,以便存放数据库。
         8、用户自己定义文件浏览框、按钮的样式。
         9、另外拥护上传成功后会返回两个属性 UrlInfoBigImage和UrlInfoSmallImage ,分别是大小图片的url路径,直接获取就可以了。   
         10、对于控件的设置,如果是新上传图片,只需要设置上传路径ComputerUrlPath属性,如果是编辑已经上传的图片,只需要对UrlInfoBigImage赋值即可。
         11、支持上传后事件,方便开发人员定义不同操作。
         12、所有的路径为相对站点根路径,比如站点为 http://localhost/nowind/images/head/1.jpg ,其中nowind为虚拟目录,则图片的UrlInfoBigImage应该为 images/head/1.jpg 注意前面不带"/"。则ComputerUrlPath应该为 images/head/

    

转载于:https://www.cnblogs.com/liufei88866/archive/2011/09/15/2177388.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值