asp.net自定义服务器控件-基于jquery的AjaxUpload封装的服务器控件

从网上多方收集,为了方便自己使用,基于jquery中的AjaxUpload插件封装成服务器控件。

示例项目结构如下:


一、MyControls为控件项目

1、控件资源

  • jquery-1.4.1.min.js-使用的jquery类库
  • ajaxupload.3.9.js   -基于ajaxupload3.9版本
  • UploadControl.js   -上传控件中的主功能的核心js
  • UploadControl.css -上传控的样式
  • loading.gif              -上传中的过渡动画
 以上资源需在项目中的Properties下的AssemblyInfo.cs文件中定义,代码如下:
 
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Web.UI;

// 有关程序集的常规信息通过下列特性集
// 控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("MyControls")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Sky123.Org")]
[assembly: AssemblyProduct("MyControls")]
[assembly: AssemblyCopyright("Copyright © Sky123.Org 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// 将 ComVisible 设置为 false 会使此程序集中的类型
// 对 COM 组件不可见。如果需要从 COM 访问此程序集中的某个类型,
// 请针对该类型将 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]

// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("110396a2-e863-49fc-b55c-82cee89a1c31")]

// 程序集的版本信息由下列四个值组成:
//
//      主版本
//      次版本
//      内部版本号
//      修订号
//
// 可以指定所有这些值,也可以使用“内部版本号”和“修订号”的默认值,
// 方法是按如下所示使用“*”:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

[assembly: WebResource("MyControls.UploadControl.UploadControl.css", "text/css", PerformSubstitution = true)]
[assembly: WebResource("MyControls.UploadControl.loading.gif", "image/gif")]
[assembly: WebResource("MyControls.UploadControl.jquery-1.4.1.min.js", "text/javascript")]
[assembly: WebResource("MyControls.UploadControl.ajaxupload.3.9.js", "text/javascript")]
[assembly: WebResource("MyControls.UploadControl.UploadControl.js", "text/javascript")]

2、核心代码

1、UploadControl.cs文件为控件核心代码,代码如下:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;

namespace MyControls
{
    [DefaultProperty("UploadControl")]
    [ToolboxData("<{0}:UploadControl runat=server></{0}:UploadControl>")]
    public class UploadControl : CompositeControl, IRequiresSessionState, IHttpHandler, IPostBackDataHandler, IScriptControl
    {
        #region 属性
        private string uploadFileDirectory = "UploadFiles";
        private string loadingImageUrl;
        private HtmlGenericControl container;
        private LinkButton btnUpload;
        private HtmlGenericControl divLoading;
        private HtmlGenericControl divFiles;
        private Button btnPost;
        private HiddenField hf_files;
        private HiddenField hf_fileTypes;
        private HiddenField hf_fileSize;

        private ScriptManager _scriptManager;

        [Browsable(false)]
        public ScriptManager scriptManager
        {
            get
            {
                if (_scriptManager != null)
                {
                    return _scriptManager;
                }
                else if (Page != null)
                {
                    ScriptManager scriptmanager = ScriptManager.GetCurrent(Page);
                    if (scriptmanager != null)
                    {
                        this._scriptManager = scriptmanager;
                        return scriptmanager;
                    }
                }
                throw new HttpException("使用UploadControl控件要求页面上必须存在ScriptManager");
            }
            set
            {
                this._scriptManager = value;
            }
        }

        [Bindable(true)]
        [Category("Appearance")]
        [DefaultValue("上传")]
        [Localizable(true)]
        [Description("上传按钮显示的文字,默认为‘上传’")]
        public string Text
        {
            get { return this.btnUpload.Text; }
            set { this.btnUpload.Text = value; }
        }

        [Bindable(true)]
        [Category("Appearance")]
        [DefaultValue("button white")]
        [Localizable(true)]
        [Description("上传按钮的css样式")]
        public string Css
        {
            get { return btnUpload.CssClass; }
            set { btnUpload.CssClass = value; }
        }

        /// <summary>
        /// 文件列表
        /// </summary>
        [Bindable(true)]
        [DefaultValue("")]
        [Localizable(true)]
        [Description("文件列表")]
        [Browsable(false)]
        public List<Attachment> Files
        {
            get
            {
                List<Attachment> res = new List<Attachment>();
                if (!string.IsNullOrEmpty(this.hf_files.Value))
                {
                    string[] strs = this.hf_files.Value.Split('|');
                    foreach (var item in strs)
                    {
                        if (!string.IsNullOrEmpty(item))
                        {
                            Attachment attach = new Attachment()
                            {
                                DisplayName = item.Split('*')[0],
                                Name = item.Split('*')[1],
                            };
                            res.Add(attach);
                        }
                    }
                }
                return res;
            }
            set
            {
                if (value.Count > 0)
                {
                    foreach (var item in value)
                    {
                        this.hf_files.Value += item.DisplayName + "*" + item.Name + "|";
                    }
                }
            }
        }

        /// <summary>
        /// 是否为多文件上传
        /// </summary>
        [Bindable(true)]
        [DefaultValue(false)]
        [Localizable(true)]
        [Description("是否为多文件上传,默认为false")]
        public bool IsMutiFileUpload
        {
            get;
            set;
        }

        /// <summary>
        /// 是否显示上传按钮
        /// </summary>
        [Bindable(true)]
        [DefaultValue(true)]
        [Localizable(true)]
        [Description("是否显示上传按钮,默认为true")]
        public bool IsShowUploadButton
        {
            get;
            set;
        }

        /// <summary>
        /// 是否显示删除按钮
        /// </summary>
        [Bindable(true)]
        [DefaultValue(true)]
        [Localizable(true)]
        [Description("是否显示删除按钮,默认为true")]
        public bool IsShowDeleteButton
        {
            get;
            set;
        }

        /// <summary>
        /// 是否显示下载按钮
        /// </summary>
        [Bindable(true)]
        [DefaultValue(true)]
        [Localizable(true)]
        [Description("是否显示下载按钮,默认为true")]
        public bool IsShowDownloadButton
        {
            get;
            set;
        }

        /// <summary>
        /// 允许上传的文件格式
        /// </summary>
        [Bindable(true)]
        [DefaultValue("*")]
        [Localizable(true)]
        [Description("允许上传的文件格式,如果为'*'代表所有文件,否则多个之间用'|'分隔 如: gif|jpg|doc,默认为'*'")]
        public string AllowFileType
        {
            get { return this.hf_fileTypes.Value; }
            set { this.hf_fileTypes.Value = value; }
        }

        /// <summary>
        /// 允许上传的文件大小
        /// </summary>
        [Bindable(true)]
        [DefaultValue("10mb")]
        [Localizable(true)]
        [Description("允许上传的文件大小,如:10kb,10mb,默认为10mb")]
        public string AllowFileSize
        {
            get { return this.hf_fileSize.Value; }
            set { this.hf_fileSize.Value = value; }
        }

        /// <summary>
        /// 允许上传的文件个数
        /// </summary>
        [Bindable(true)]
        [DefaultValue(1)]
        [Localizable(true)]
        [Description("允许上传的文件个数 默认为1")]
        public string AllowFileCount
        {
            get { return btnUpload.Attributes["MaxFileCount"]; }
            set { btnUpload.Attributes["MaxFileCount"] = value; }
        }

        /// <summary>
        /// 是否自动初始化控件相关的web.config配置
        /// </summary>
        [Bindable(true)]
        [DefaultValue(false)]
        [Localizable(true)]
        [Description("是否自动初始化控件相关的web.config配置")]
        public bool IsAutoInitConfig
        {
            get;
            set;
        }
        #endregion

        #region 事件
        public UploadControl()
        {
            EnsureChildControls();
        }

        /// <summary>
        /// 创建内容控件(最先执行)
        /// </summary>
        protected override void CreateChildControls()
        {
            base.CreateChildControls();

            container = new HtmlGenericControl("div");
            container.ID = "Container";
            this.Controls.Add(container);

            btnUpload = new LinkButton();
            btnUpload.ID = "btnUpload";
            btnUpload.CssClass = Css;
            btnUpload.Style.Add("float", "left");

            divLoading = new HtmlGenericControl("div");
            divLoading.ID = "divLoading";
            divLoading.Style.Add("float", "left");
            divLoading.Style.Add("padding-left", "2px");

            divFiles = new HtmlGenericControl("div");
            divFiles.ID = "divFiles";
            divFiles.Style.Add("float", "left");
            divFiles.Style.Add("padding-left", "5px");

            btnPost = new Button();
            btnPost.ID = "btnPost";
            btnPost.Style.Add("display", "none");

            hf_files = new HiddenField();
            hf_files.ID = "hf_files";

            container.Controls.Add(btnUpload);
            container.Controls.Add(divLoading);
            container.Controls.Add(divFiles);
            container.Controls.Add(btnPost);
            container.Controls.Add(hf_files);

            hf_fileTypes = new HiddenField();
            hf_fileTypes.ID = "hf_fileTypes";

            hf_fileSize = new HiddenField();
            hf_fileSize.ID = "hf_fileSize";

            this.Controls.Add(hf_fileTypes);
            this.Controls.Add(hf_fileSize);

            //设置默认值写在这里最合适
            SetAttributeDefaultValue();

            btnUpload.Attributes.Add("MaxFileCount", this.AllowFileCount);
        }

        /// <summary>
        /// 加载事件(在CreateChildControls之后执行)
        /// </summary>
        /// <param name="e"></param>
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            loadingImageUrl = this.Page.ClientScript.GetWebResourceUrl(this.GetType(), "MyControls.UploadControl.loading.gif");

            Page.ClientScript.RegisterStartupScript(this.GetType(), this.ClientID + "_ReInit", @"<script type='text/javascript'>var prm = Sys.WebForms.PageRequestManager.getInstance();prm.add_endRequest(function () {$(document).ready(function () {Init('" + this.ClientID + "','" + loadingImageUrl + "');});});</script>");

            if (IsShowUploadButton)
                this.btnUpload.Visible = true;
            else
                this.btnUpload.Visible = false;
            if (IsMutiFileUpload)
                MultiFile();
            else
                SingleFile();
        }

        /// <summary>
        /// PreRender事件(在OnLoad之后执行)
        /// </summary>
        /// <param name="e"></param>
        protected override void OnPreRender(EventArgs e)
        {
            Page.RegisterRequiresPostBack(this);

            base.OnPreRender(e);

            if (IsAutoInitConfig)
            {
                ConfigManager.AddUploadDirectoryConfig("UploadFilePath", "UploadFiles");
                //ConfigManager.RegisterControlConfig();
                ConfigManager.AddRequestConfig(2097150, 3600);
                ConfigManager.AddRequestSecurityConfig();
                ConfigManager.AddAsyncAjaxConfig();
            }

            if (!DesignMode)
            {
                this.scriptManager.RegisterScriptControl<UploadControl>(this);

                HtmlLink link = Page.Header.FindControl("UploadControlCSS") as HtmlLink;
                if (link == null) //防止重复
                {
                    link = new HtmlLink();
                    link.ID = "UploadControlCSS";
                    link.Attributes["type"] = "text/css";
                    link.Href = Page.ClientScript.GetWebResourceUrl(this.GetType(), "MyControls.UploadControl.UploadControl.css");
                    link.Attributes["rel"] = "stylesheet";
                    Page.Header.Controls.Add(link);
                }
                Page.ClientScript.RegisterClientScriptResource(this.GetType(), "MyControls.UploadControl.jquery-1.4.1.min.js");
                Page.ClientScript.RegisterClientScriptResource(this.GetType(), "MyControls.UploadControl.ajaxupload.3.9.js");

                //这句可以不要 在GetScriptReferences()方法也可以做
                //Page.ClientScript.RegisterClientScriptResource(this.GetType(), "MyControls.UploadControl.UploadControl.js");

                Page.ClientScript.RegisterStartupScript(this.GetType(), this.ClientID + "_Init", "<script>$(document).ready(function () {Init('" + this.ClientID + "','" + loadingImageUrl + "');});</script>");
            }
        }
        #endregion

        #region 方法
        /// <summary>
        /// 设置属性的默认值
        /// </summary>
        void SetAttributeDefaultValue()
        {
            this.Text = "上传";
            //this.Css = "button white";
            this.AllowFileType = "*";
            this.AllowFileSize = "10mb";
            this.AllowFileCount = "1";
            this.IsMutiFileUpload = false;
            this.IsShowUploadButton = true;
            this.IsShowDeleteButton = true;
            this.IsShowDownloadButton = true;
            this.IsAutoInitConfig = false;

            if(ConfigurationManager.AppSettings["UploadFilePath"]!=null)
                uploadFileDirectory = ConfigurationManager.AppSettings["UploadFilePath"].ToString();
        }

        /// <summary>
        /// 单文件上传时输出
        /// </summary>
        void SingleFile()
        {
            string uploadPath =uploadFileDirectory;
            string innerHtml = string.Empty;
            if (Files.Count > 0)
            {
                int fileIndex = Files.Count - 1;
                var item = Files[fileIndex];
                for (int i = 0; i < Files.Count; i++)
                {
                    //总是删除之前的,用最新的一个替换
                    if (i != fileIndex)
                        File.Delete(Page.Server.MapPath(string.Format("~/{0}/", uploadPath)) + Files[i].Name);
                }
                this.hf_files.Value = item.DisplayName + "*" + item.Name + "|";
                innerHtml = string.Format("<span title='{0}'>{1}</span> {2} {3}", item.DisplayName, FormatItem(item.DisplayName), GetDeleteHTML(item.Name), GetDownloadHTML(item.DisplayName, item.Name));
            }
            divFiles.InnerHtml = innerHtml;
        }

        /// <summary>
        /// 多文件上传时输出
        /// </summary>
        void MultiFile()
        {
            string innerHtml = string.Empty;
            foreach (var item in Files)
            {
                innerHtml += string.Format("<li><span title='{0}'>{1}</span> {2} {3}</li>", item.DisplayName, FormatItem(item.DisplayName), GetDeleteHTML(item.Name), GetDownloadHTML(item.DisplayName, item.Name));
            }
            if (Files.Count > 0)
            {
                innerHtml = "<ul>" + innerHtml + "</ul>";
                divFiles.Style["padding-left"] = "5px";
                divFiles.Style["padding-top"] = "20px";
                divFiles.Style.Remove("float");

            }
            divFiles.InnerHtml = innerHtml;
        }

        /// <summary>
        /// 获取删除html串
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        string GetDeleteHTML(string fileName)
        {
            if (IsShowDeleteButton)
                return string.Format("<a href='#' οnclick='RemoveFile(\"{0}\",\"{1}\",\"{2}\")'>删除</a>",this.ClientID, fileName,loadingImageUrl);
            else
                return string.Empty;
        }

        /// <summary>
        /// 获取下载html串
        /// </summary>
        /// <returns></returns>
        string GetDownloadHTML(string displayName, string fileName)
        {
            if (IsShowDownloadButton)
            {
                var showName = Page.Server.UrlEncode(displayName);
                var realName = Page.Server.UrlEncode(fileName);

                string Path = Page.Server.UrlDecode(uploadFileDirectory);//文件路径
                string path = Page.Server.MapPath(Path) + "\\" + fileName;
                if (File.Exists(path))
                    return string.Format("<a href='MyControls?Action=Download&DisplayName={0}&FileName={1}'>下载</a>", showName, realName);
                else
                    return string.Format("<a target='_blank' href='MyControls?Action=Download&DisplayName={0}&FileName={1}'>下载</a>", showName, realName);
            }
            else
                return string.Empty;
        }

        /// <summary>
        /// 格式化长度
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        string FormatItem(string item)
        {
            int maxLength = 15;
            return getStr(item, maxLength, "...");
        }

        /// <summary>
        /// 根据字符串s超过指定长度l时,对结尾endStr的处理
        /// </summary>
        /// <param name="s"></param>
        /// <param name="l"></param>
        /// <param name="endStr"></param>
        /// <returns></returns>
        string getStr(string s, int l, string endStr)
        {
            string temp = s.Substring(0, (s.Length < l + 1) ? s.Length : l + 1);
            byte[] encodedBytes = System.Text.ASCIIEncoding.ASCII.GetBytes(temp);

            string outputStr = "";
            int count = 0;

            for (int i = 0; i < temp.Length; i++)
            {
                if ((int)encodedBytes[i] == 63)
                    count += 2;
                else
                    count += 1;

                if (count <= l - endStr.Length)
                    outputStr += temp.Substring(i, 1);
                else if (count > l)
                    break;
            }

            if (count <= l)
            {
                outputStr = temp;
                endStr = "";
            }

            outputStr += endStr;

            return outputStr;
        }
        #endregion

        #region IPostBackDataHandler相关
        public bool LoadPostData(string postDataKey, System.Collections.Specialized.NameValueCollection postCollection)
        {
            return true;
        }

        public void RaisePostDataChangedEvent()
        {

        }
        #endregion

        #region IHttpHandler相关
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        public void ProcessRequest(HttpContext context)
        {
            try
            {
                if (context.Request["Action"] != null)
                {
                    switch (context.Request["Action"].ToString())
                    {
                        case "Upload":
                            Upload(context);
                            break;
                        case "Remove":
                            Remove(context);
                            break;
                        case "Download":
                            Download(context);
                            break;
                    }
                }
            }
            catch (Exception ex)
            {
                context.Response.Write("error|" + ex.Message);
            }
        }

        /// <summary>
        /// 上传附件
        /// </summary>
        /// <param name="context"></param>
        void Upload(HttpContext context)
        {
            double MaxFileSize = GetMaxSize(context.Request["FileSize"].ToString());
            HttpPostedFile hpfFile = context.Request.Files["uploadfile"];
            if (hpfFile.ContentLength <= MaxFileSize)
            {
                string[] strs = hpfFile.FileName.Split('.');
                string extName = strs[strs.Length - 1];
                string fileName = "p" + Guid.NewGuid().ToString().Replace("-", "") + "." + extName;
                string path = context.Server.MapPath(string.Format("~/{0}/", uploadFileDirectory));
                if (!Directory.Exists(path))
                    Directory.CreateDirectory(path);
                hpfFile.SaveAs(path + fileName);
                context.Response.Write("success|" + fileName);
            }
            else
                context.Response.Write("success|big");
        }

        /// <summary>
        /// 移除附件
        /// </summary>
        /// <param name="context"></param>
        void Remove(HttpContext context)
        {
            var fileName = context.Request["FileName"].ToString();
            File.Delete(context.Server.MapPath(string.Format("~/{0}/", uploadFileDirectory)) + fileName);
            context.Response.Write("success");
        }

        /// <summary>
        /// 下载附件
        /// </summary>
        /// <param name="context"></param>
        void Download(HttpContext context)
        {
            string Path = context.Server.UrlDecode(uploadFileDirectory);//文件路径
            string DisplayName = context.Server.UrlDecode(context.Request["DisplayName"]);//文件显示的名称
            string FileName = context.Server.UrlDecode(context.Request["FileName"]);//实际文件名称

            if (!string.IsNullOrEmpty(Path))
            {
                string path = context.Server.MapPath(Path) + "\\" + FileName;
                if (File.Exists(path))
                {
                    using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))
                    {
                        byte[] btFile = new byte[fs.Length];
                        fs.Read(btFile, 0, Convert.ToInt32(fs.Length));
                        Output(context, DisplayName, btFile);
                    }
                }
                else
                {
                    context.Response.Write("<script>alert('文件不存在');window.opener=null;window.open('','_self');window.close();</script>");
                }
            }
        }

        /// <summary>
        /// 最大文件的大小(单位为字节)
        /// </summary>
        /// <param name="fileSize"></param>
        /// <returns></returns>
        double GetMaxSize(string fileSize)
        {
            double res = -1;
            if (fileSize.Contains("mb"))
                res = double.Parse(fileSize.Replace("mb", "").Trim()) * 1024 * 1024;
            if (fileSize.Contains("kb"))
                res = double.Parse(fileSize.Replace("kb", "").Trim()) * 1024;
            return res;
        }

        /// <summary>
        /// 输出附件
        /// </summary>
        void Output(HttpContext context, string fileName, byte[] obj)
        {
            context.Response.Clear();
            context.Response.BufferOutput = false;
            context.Response.ContentEncoding = System.Text.Encoding.UTF8;
            context.Response.AddHeader("Content-Disposition", "attachment;filename=" + context.Server.UrlEncode(fileName));
            context.Response.ContentType = "application/octet-stream";
            context.Response.OutputStream.Write(obj, 0, obj.Length);
            context.Response.Close();
            context.Response.End();
        }
        #endregion

        #region IScriptControl相关
        public IEnumerable<ScriptDescriptor> GetScriptDescriptors()
        {
            ScriptControlDescriptor descriptor = new ScriptControlDescriptor("MyControls.UploadControl", this.ClientID);
            yield return descriptor;
        }

        public IEnumerable<ScriptReference> GetScriptReferences()
        {
            yield return new ScriptReference("MyControls.UploadControl.UploadControl.js", this.GetType().Assembly.FullName);
        }
        #endregion
    }
}
2、Attachment.cs文件为附件类,代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MyControls
{
    /// <summary>
    /// 附件类
    /// </summary>
    public class Attachment
    {
        /// <summary>
        /// 附件ID
        /// </summary>
        public string ID
        {
            get;
            set;
        }

        /// <summary>
        /// 附件名称
        /// </summary>
        public string Name
        {
            get;
            set;
        }

        /// <summary>
        /// 附件显示名称
        /// </summary>
        public string DisplayName
        {
            get;
            set;
        }

        /// <summary>
        /// 附件路径
        /// </summary>
        public string Path
        {
            get;
            set;
        }
    }
}

二.MyControls.Test为测试项目

示例图:


1、UploadFiles-该目录为控件默认上传附件的目录,可以在web.config文件中配置

2、Default.aspx-文件为控件demo页面,代码如下:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="MyControls.Test.Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
<style type="text/css">
<!--
.onediv{width:300px; height:300px;float:left;margin:0 0 0 5px; border:1px #000 solid;}
.twodiv{width:300px; height:300px;float:left;margin:0 0 0 5px; border:1px #000 solid;}
-->
</style>
</head>
<body>
    <form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
            <ContentTemplate>
            <div class="onediv">
                <span>单文件上传</span><p/>
                <asp:UploadControl runat="server" ID="UploadControl1" Text="浏览" AllowFileSize="50mb" Css="button white"/>
            </div>
            <div class="twodiv">
                <span>多文件上传</span><p/>
                <asp:UploadControl runat="server" ID="UploadControl2" Text="浏览" 
                IsMutiFileUpload="true" AllowFileSize="70mb"
                AllowFileCount="1000" IsAutoInitConfig="false" Css="button white"/>
                
            </div>
            <div class="onediv"><ul id="ul1" runat="server"></ul></div>
            <div class="onediv"><ul id="ul2" runat="server"></ul></div>
            <asp:Button ID="Button1" runat="server" Text="测试回发" OnClick="Button1_Click"/>
            </ContentTemplate>
        </asp:UpdatePanel>
    </form>
</body>
</html>
Default.aspx.cs对应后台代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace MyControls.Test
{
    public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                List<Attachment> list = new List<Attachment>();
                list.Add(new Attachment()
                {
                    DisplayName = "aa.docx",
                    Name = "aa.docx",
                });
                UploadControl1.Files = list;

                list.Add(new Attachment()
                {
                    DisplayName = "bb.docx",
                    Name = "bb.docx",
                });
                UploadControl2.Files = list;
                Button1_Click(null, null);
            }
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            var list1 = UploadControl1.Files;
            var list2 = UploadControl2.Files;

            ul1.InnerHtml = string.Empty;
            ul2.InnerHtml = string.Empty;

            foreach (var item in list1)
            {
                ul1.InnerHtml += "<li>" + item.DisplayName + "</li>";
            }

            foreach (var item in list2)
            {
                ul2.InnerHtml += "<li>" + item.DisplayName + "</li>";
            }
        }
    }
}

3.Web.config文件配置如下:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.5" />
    <pages controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID">
      <controls>
        <!-- 注册控件,避免每个页面中引用时都要注册 -->
        <add assembly="MyControls" namespace="MyControls" tagPrefix="asp" />
      </controls>
    </pages>
    <!--本句用来设置允许最大请求长度,上传太大的文件受此参数限制-->
    <httpRuntime maxRequestLength="2097150" executionTimeout="3600" />
  </system.web>
  <appSettings>
    <!--上传附件默认存放在目录-->
    <add key="UploadFilePath" value="UploadFiles" />
  </appSettings>
  <system.webServer>
    <security>
      <requestFiltering>
        <requestLimits maxAllowedContentLength="2147483647" />
      </requestFiltering>
    </security>
    <handlers>
      <!--本节用来实现控件内异步ajax请求  使用此控件必须要加这一句-->
      <add verb="POST,GET" name="Uploader" type="MyControls.UploadControl,MyControls" path="MyControls" />
    </handlers>
  </system.webServer>
</configuration>
三、缺陷和不足之处

  • 不支持进度条,希望高手指点;
  • 控件在本机vs和iis网站中运行正常,但是上传到外网服务器上运行有问题,ajax请求有问题,没查出来;
  • 还有的等待进一步发现
 希望路过的帮忙完善,谢谢!




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值