zoukankan      html  css  js  c++  java
  • 自写的上传自定义控件

    控件类文件:

    ======================================================================================

    using System;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.ComponentModel;
    using System.Collections;
    using System.Collections.Specialized;
     
    namespace PublicControls
    {
         ///<summary>
         /// UpLoadFile 的摘要说明。
         ///</summary>
         [DefaultProperty("Text"),
         ToolboxData("<PublicControls:UpLoadFile runat=server></PublicControls:UpLoadFile>")]
         public class UpLoadFile : System.Web.UI.WebControls.WebControl,IPostBackDataHandler,IPostBackEventHandler
         {
             #region预定义
             private string _url;
             private string _type;
             private string _uploadpagepath;
             private string _uploadsavepath;
             private string js;
     
             ///<summary>
             ///委托页面索引事件
             ///</summary>
             public event EventHandler UrlChanged;
     
             #endregion
     
             #region属性
             ///<summary>
             ///关联的文件的Url地址
             ///</summary>
             public string Url
             {
                  get
                  {
                       if ((string)(ViewState["Url"]+"")!="")
                       {
                           _url = (string)ViewState["Url"];
                       }
                       return _url;
                  }
                  set
                  {
                       _url = value;
                       ViewState["Url"] = _url;
                  }
             }
     
             ///<summary>
             ///上传类型,all为所有类型,自定义使用‘,’分割开,如:“jpg,gif,jpeg,png”
             ///</summary>
             public string Type
             {
                  get
                  {
                       if ((string)(ViewState["Type"]+"")!="")
                       {
                           _type = (string)ViewState["Type"];
                       }
                       else
                       {
                           _type = "all";
                       }
                       return _type;
                  }
                  set
                  {
                       _type = value;
                       ViewState["Type"] = _type;
                  }
             }
     
             ///<summary>
             ///上传模态文件地址
             ///</summary>
             public string UpLoadPagePath
             {
                  get
                  {
                       if ((string)(ViewState["UpLoadPagePath"]+"")!="")
                       {
                           _uploadpagepath = (string)ViewState["UpLoadPagePath"];
                       }
                       else
                       {
                           _uploadpagepath = "UploadControl.aspx";
                       }
                       return _uploadpagepath;
                  }
                  set
                  {
                       _uploadpagepath = value;
                       ViewState["UpLoadPagePath"] = _uploadpagepath;
                  }
              }
     
             ///<summary>
             ///上传的文件保存地址
             ///</summary>
             public string UpLoadSavePath
             {
                  get
                  {
                       if ((string)(ViewState["UpLoadSavePath"]+"")!="")
                       {
                           _uploadsavepath = (string)ViewState["UpLoadSavePath"];
                       }
                       else
                       {
                           _uploadsavepath = "Upload";
                       }
                       return _uploadsavepath;
                  }
                  set
                  {
                       _uploadsavepath = value;
                  }
             }
     
             #endregion
     
             #region事件
     
             ///<summary>
             ///获取回发的数据
             ///</summary>
             ///<param name="postDataKey"></param>
             ///<param name="values"></param>
             ///<returns></returns>
             public bool LoadPostData(String postDataKey, NameValueCollection values)
             {
                  if(Url != values[this.UniqueID])
                  {
                       Url = values[this.UniqueID];
                       return true;
                  }
                  else
                  {
                       return false;
                  }
            
             }
     
             ///<summary>
             ///数据回发事件
             ///</summary>
             public void RaisePostDataChangedEvent()
             {
                  OnUrlChanged(System.EventArgs.Empty);
             }
     
             ///<summary>
             ///回送事件
             ///</summary>
             ///<param name="e"></param>
             public void RaisePostBackEvent(string e)
             {
             }
     
             ///<summary>
             ///输出预处理
             ///</summary>
             ///<param name="e"></param>
             protected override void OnPreRender(EventArgs e)
             {
                  js = "";
                  js += "<script>";
                  js += "function OpenModal(){";
                  js += "var k = window.showModalDialog('"+UpLoadPagePath+"?type="+Type+"&savepath="+UpLoadSavePath+"','','dialogHeight:120px;status:no');";
                  js += "if(k!=null)";
                  js += "{ document.all."+this.UniqueID+".value = k;}";
                  js += "}";
                  js += "</script>";
            
             }
     
             ///<summary>
             ///引发事件方法
             ///</summary>
             ///<param name="e"></param>
             protected void OnUrlChanged(EventArgs e)
             {
                  if(UrlChanged!=null)
                  {
                       UrlChanged(this,e);
                  }
             }
     
             #endregion
     
             #region输出
             ///<summary>
             ///将此控件呈现给指定的输出参数。
             ///</summary>
             ///<param name="output">要写出到的 HTML 编写器 </param>
             protected override void Render(HtmlTextWriter output)
             {
                  string outputstring = "";
        
                  outputstring += js;
                  outputstring += "<input name = "+this.UniqueID+" type = 'text' value = '"+this.Url+"'>";
                  outputstring += "<input type = 'button' value='上传' onclick='OpenModal()'>";
                  output.Write(outputstring);
             }
             #endregion
         }
    }
     模态加载文件:
    ====================================================================================
    <%@ Page language="c#" %>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
    <HTML>
     <HEAD>
      <title>UpLoadControl</title>
      <script language="C#" runat="server">
    private void Page_Load(object sender, System.EventArgs e)
    {
     if(!Page.IsPostBack)
     {
      string type = Request.QueryString["type"];
      if (type=="all")
      {
       er.ValidationExpression = ".*";
      }
      else
      {
       string[] types;
       types = type.Split(',');
       string typestr = "";
       for(int i = 0;i<types.Length;i++)
       {
        typestr += "//."+types[i];
        if(i<types.Length-1)
        {
         typestr += "|";
        }
       }
       
       er.ValidationExpression = ".*("+typestr+")";
      }
     }
    }
    private void btnClick(object sender,System.EventArgs e)
    {
     Page.Validate();
     if(Page.IsValid)
     {
     string savepath = Request.QueryString["savepath"];
     string url=savepath+"/"+ UpLoad(savepath);
     Response.Write("<script>window.returnValue = '"+url+"'</");
     Response.Write("script>");
     Response.Write("<script>window.close()</");
     Response.Write("script>");
     }
    }
    string UpLoad(string Path)
    {
     string msg = null;
     if(UpfileBox.PostedFile.ContentLength>0)
     {
      try
      {
       Path = Server.MapPath(Path)+"/";
       string fileName = DateTime.Now.ToString("yyyMMddhhmmss")+DateTime.Now.Millisecond.ToString(); //生成时间文件名
       string fileSub = UpfileBox.PostedFile.FileName;   //获得上传文件路径和文件名
       int i = fileSub.Split('.').Length;      //以‘.’为分割,分割文件本地路径
       fileSub = "."+fileSub.Split('.')[i-1].ToString();  //最后一个‘.’以后的部分作为文件的后缀
       UpfileBox.PostedFile.SaveAs(Path+fileName+fileSub);  //保存文件
       msg = fileName+fileSub;         //将文件名赋予msg变量准备返回
      }
      catch
      {
       msg = "";
      }
      finally
      {
      }
     }
     else
     {
      msg = "";
     }
     UpfileBox.Dispose();
     return msg;
      }
      </script>
      <meta content="Microsoft Visual Studio .NET 7.1" name="GENERATOR">
      <meta content="C#" name="CODE_LANGUAGE">
      <meta content="JavaScript" name="vs_defaultClientScript">
      <meta content="http://schemas.microsoft.com/intellisense/ie5" name="vs_targetSchema">
      <base target="_self">
     </HEAD>
     <body>
      <form id="Form1" method="post" encType="multipart/form-data" runat="server">
       <P align="center"><BR>
        <INPUT id="UpfileBox" type="file" name="File1" runat="server">
        <asp:button id="btn" onclick="btnClick" runat="server" Text="上传"></asp:button><asp:regularexpressionvalidator id="er" runat="server" ValidationExpression=".*" Display="Dynamic" ControlToValidate="UpfileBox"
         ErrorMessage="上传的文件错误"></asp:regularexpressionvalidator></P>
      </form>
     </body>
    </HTML>
  • 相关阅读:
    Python--IO模型
    python queue, pipe, manage
    python多线程,event,互斥锁,死锁,递归锁,信号量
    day34 异常处理、断言、socket之ftp协议
    day34 反射、面向对象内置方法:如__str__、面向对象的软件开发
    PHP基础入门(二)【PHP函数基础】
    PHP基础入门详解(一)【世界上最好用的编程语言】
    H5简单拖放(Drag/Drop)
    手机APP ~ MUI——创建页面方法
    bootstrap栅格系统
  • 原文地址:https://www.cnblogs.com/ZetaChow/p/2237445.html
Copyright © 2011-2022 走看看