Asp.Net Web控制項 (一)(上傳控制項)

來源:互聯網
上載者:User

這個控制項就是對 cloudgamer 的 仿163網盤無重新整理多檔案上傳系統 封裝,使我們使用更加簡單方便。

先來看效果:

<hxj:UploadControl ID="uploadfile" runat="server" MaxFileNumbers="5" AllowExtensions="jpg,gif" /><asp:Button ID="Button1" runat="server" Text="上傳" OnClick="Button1_Click" />

html的代碼簡單,設計時如下:

在設計時狀態下並不好看,因為沒有載入樣式。

預覽效果:

預覽後載入了樣式效果好看多了。

配合後台代碼:

protected void Button1_Click(object sender, EventArgs e){    Hxj.Web.UploadFile uf = new Hxj.Web.UploadFile();    //設定路徑    //uf.FilePath = "~/";     //上傳檔案資訊    List<Hxj.Web.UploadFileInfo> filelist = uf.UploadAll();}

檔案很輕鬆就上傳。

這裡取消了原來無重新整理上傳功能。

 

 

下面講述如何封裝成Asp.Net Web控制項。

首先建立一個類繼承Control

[ToolboxData("<{0}:UploadControl runat=\"server\"></{0}:UploadControl>")]public class UploadControl : Control

 

在這個控制項中有兩個屬性,一個是上傳檔案數量、另外一個是允許上傳的檔案類型,

如下:

[Category("Behavior")][DefaultValue(0)][Description("最多上傳檔案數 0表述無限制")]public int MaxFileNumbers{    get    {        object s = ViewState["_MaxFileNumbers.Hxj.Web.UI.UploadControl"];        int numbers = 0;        if (null == s)            return numbers;        int.TryParse(s.ToString(), out numbers);        if (numbers < 0)            numbers = 0;        return numbers;    }    set    {        ViewState["_MaxFileNumbers.Hxj.Web.UI.UploadControl"] = value;    }}[Category("Behavior")][DefaultValue("*")][Description("允許上傳的副檔名,用逗號隔開,所有檔案請用 * ")]public string AllowExtensions{    get    {        object extension = ViewState["_AllowExtensions.Hxj.Web.UI.UploadControl"];        if (null == extension)            return "*";        return extension.ToString();    }    set    {        ViewState["_AllowExtensions.Hxj.Web.UI.UploadControl"] = value;    }}

 

接下來是輸出需要呈現的Html資訊,在void Render(HtmlTextWriter writer)事件中輸出Html,

代碼如下:

protected override void Render(HtmlTextWriter writer){    //驗證該控制項必須添加在 Form 表單中, 否則異常    if (null != Page)    {        Page.VerifyRenderingInServerForm(this);    }    StringBuilder html = new StringBuilder();    html.Append("<table border=\"0\" cellspacing=\"1\" class=\"fu_list\" id=\"");    html.Append(this.ClientID);    html.Append("\"><tbody><tr><td align=\"right\" width=\"15%\" style=\"line-height:35px;\">添加檔案:</td><td><a href=\"javascript:void(0);\" class=\"files\" id=\"");    html.Append(this.ClientID);    html.Append("File\"></a> <img id=\"");    html.Append(this.ClientID);    html.Append("Process\" style=\"display:none;\" src=\"img/loading.gif\" /></td><td align=\"center\"><input type=\"button\" value=\"全部取消\" id=\"");    html.Append(this.ClientID);    html.Append("Btndel\" disabled=\"disabled\" /></td></tr><tr><td colspan=\"3\"><table border=\"0\" cellspacing=\"0\"><thead><tr><td>檔案路徑</td><td width=\"100\"></td></tr></thead><tbody id=\"");    html.Append(this.ClientID);    html.Append("FileList\"></tbody></table></td></tr>");    if (MaxFileNumbers > 0 || !IsAllowAll())     {        html.Append("<tr><td colspan=\"3\" style=\"color:gray\">溫馨提示:");        if (MaxFileNumbers > 0)        {            html.Append("最多可同時上傳 <b id=\"");            html.Append(this.ClientID);            html.Append("Limit\"></b> 個檔案,");        }        if (!IsAllowAll())        {            html.Append("只允許上傳 <b id=\"");            html.Append(this.ClientID);            html.Append("Ext\"></b> 檔案。");        }        html.Append("</td></tr>");    }    html.Append("</tbody></table>");    writer.Write(html.ToString());}

這樣的寫法比較亂,不是推薦的寫法。

 

接下來就是引用指令碼,引用css,輸出指令碼,在void OnPreRender(EventArgs e)事件中完成。

代碼如下:

protected override void OnPreRender(EventArgs e){    this.Page.Form.Attributes.Remove("enctype");    this.Page.Form.Attributes.Add("enctype", "multipart/form-data");    if (!Page.ClientScript.IsClientScriptIncludeRegistered("UploadControlJS"))        Page.ClientScript.RegisterClientScriptInclude("UploadControlJS", Page.ClientScript.GetWebResourceUrl(this.GetType(), "Hxj.Web.UI.js.fileupload.js"));    string strCssLink = string.Concat("<link href='", this.Page.ClientScript.GetWebResourceUrl(this.GetType(), "Hxj.Web.UI.css.fileupload.css"), "' rel='stylesheet' type='text/css' />");    string cssKey = "UploadControlCSS";    if (Page.Header.FindControl(cssKey) == null)    {        Literal ltlCss = new Literal();        ltlCss.ID = cssKey;        ltlCss.Text = strCssLink;        this.Parent.Page.Header.Controls.Add(ltlCss);    }    StringBuilder script = new StringBuilder();    script.AppendLine();    script.Append("var ");    script.Append(this.ClientID);    script.Append("fu = new FileUpload(\"");    script.Append(this.Page.Form.ClientID);    script.Append("\", \"");    script.Append(this.ClientID);    script.Append("File\", { Limit:");    if (MaxFileNumbers == 0)    {        script.Append("9999");    }    else    {        script.Append(MaxFileNumbers.ToString());    }    script.Append(", ");    if (!IsAllowAll())    {        script.Append(" ExtIn:[");        string extensions = AllowExtensions;        if (!string.IsNullOrEmpty(extensions))        {            StringBuilder extin = new StringBuilder();            string[] exts = extensions.Split(',');            foreach (string ext in exts)            {                extin.Append(",");                extin.Append("\"");                extin.Append(ext);                extin.Append("\"");            }            script.Append(extin.ToString().Substring(1));        }        script.AppendLine("],");    }        script.Append("FileName: \"");    script.Append(this.ClientID);    script.AppendLine("mf\",");    script.AppendLine("onIniFile: function(file){ file.value ? file.style.display = \"none\" : this.Folder.removeChild(file); },");    script.AppendLine("onEmpty: function(){ alert(\"請選擇一個檔案\"); },");    script.AppendLine("onLimite: function(){ alert(\"最多隻能同時上傳\" + this.Limit + \"個檔案\"); },");    script.AppendLine("onSame: function(){ alert(\"已經有相同檔案\"); },");    script.AppendLine("onNotExtIn: function(){ alert(\"只允許上傳\" + this.ExtIn.join(\",\") + \"檔案\"); },");    script.AppendLine("onExtOut: function(){ alert(\"禁止上傳\" + this.ExtOut.join(\",\") + \"檔案\"); },");    script.AppendLine("onFail: function(file){ this.Folder.removeChild(file); },");    script.Append(@"onIni: function(){ var arrRows = [];if(this.Files.length){    var oThis = this;    Each(this.Files, function(o){        var a = document.createElement(""a""); a.innerHTML = ""取消""; a.href = ""javascript:void(0);"";        a.onclick = function(){ oThis.Delete(o); return false; };        arrRows.push([o.value, a]);    });} else { arrRows.push([""<font color='gray'>沒有添加檔案</font>"", ""&nbsp;""]); }AddList(arrRows,""");    script.Append(this.ClientID);    script.Append("FileList\");");    script.Append(" $(\"");    script.Append(this.ClientID);    script.Append("Btndel\").disabled = this.Files.length <= 0;}});");    if (MaxFileNumbers > 0)    {        script.Append("$(\"");        script.Append(this.ClientID);        script.Append("Limit\").innerHTML = ");        script.Append(this.ClientID);        script.Append("fu.Limit;");    }    if (!IsAllowAll())    {        script.Append("$(\"");        script.Append(this.ClientID);        script.Append("Ext\").innerHTML = ");        script.Append(this.ClientID);        script.Append("fu.ExtIn.join(\",\");");    }        script.Append("$(\"");    script.Append(this.ClientID);    script.Append("Btndel\").onclick = function(){ ");    script.Append(this.ClientID);    script.Append("fu.Clear(); }");    if (!this.Page.ClientScript.IsStartupScriptRegistered("UploadControlStartscript"))        this.Page.ClientScript.RegisterStartupScript(typeof(string), "UploadControlStartscript", script.ToString(), true);    base.OnPreRender(e);}

 

當然還需資源檔的引用。

[assembly: WebResource("Hxj.Web.UI.js.fileupload.js", "text/javascript")][assembly: WebResource("Hxj.Web.UI.css.fileupload.css", "text/css", PerformSubstitution = true)][assembly: WebResource("Hxj.Web.UI.img.fu_btn.gif", "img/gif")]

 

其中PerformSubstitution 屬性設定為true表示對其他資源檔有引用,這裡是引用了Hxj.Web.UI.img.fu_btn.gif這個圖片。

這裡的WebResource的第一個參數的組成是程式集+路徑+資源檔名。

 

這樣一個控制項就封裝完畢了。

 

下載 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.