0
点赞
收藏
分享

微信扫一扫

自定义表单设计之九-自定义表单中上传附件

附件模块,在自定义表单中,有附件类型字段时,渲染出附件按钮,点击按钮弹出附件上传模块。

附件上传时要记录表单id。

自定义表单设计之九-自定义表单中上传附件_附件上传

自定义表单设计之九-自定义表单中上传附件_自定义表单_02

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="../JavaScript/jquery.js" type="text/javascript"></script>
    <script type="text/javascript">
        function removeAttach(aid, doma) {
            if (confirm("您真的要删除此附件吗?")) {
                $.ajax({
                    type: "POST",
                    contentType: "application/json",
                    url: "../WebServices/OrdersService.asmx/DeteleAttach",
                    data: "{attchID:'" + aid + "'}",
                    dataType: 'json',
                    success: function (result) {
                        if (result.d > 0) {
                            //deleted
                            $(doma).parent().remove();
                        }
                    }
                });
            }
        }

        //附件添加
        function addFile() {
            $(".addFile:last, .delFile:last").css('visibility', 'hidden');
            $("#MyFile").append("<li><input type='file'  name='File' style='width:250px;'/><img src='../Images/button_append.gif' alt='添加附件' class='addFile' onclick='addFile()' /><img src='../Images/button_delete.gif' alt='删除附件' class='delFile' onclick='delFile()' /></li>");

        };

        function delFile() {
            $("#MyFile li:last").remove();
            $(".addFile:last, .delFile:last").css('visibility', 'visible');
        }
    </script>
</head>
<body>
    <form id="form1" runat="server" enctype="multipart/form-data">
    <div>
        <table>
            <tr>
                <td valign="middle" align="center" colspan="2">
                    <ol id="MyFile">
                        <li>
                            <input type='file' name='File' style='width: 250px' /><img src='../Images/button_append.gif'
                                alt='添加附件' class='addFile' onclick='addFile()' /></li></ol>
                    <div style="text-align: right; padding-right: 10px; padding-top: 10px;">
                        <asp:Button ID="btnUpLoad" runat="server" Text="上传" OnClick="btnUpLoad_Click" /><br />
                        <asp:Label ID="lblMsg" runat="server" />
                    </div>
                </td>
            </tr>
            <tr>
               
                <td style="width: auto;">
                    <asp:Literal runat="server" ID="UploadObjectLiteral"></asp:Literal>
                </td>
            </tr>
        </table>
    </div>
    </form>
</body>
</html>

后端代码

#region EventHandler
        protected void btnUpLoad_Click(object sender, EventArgs e)
        {
            int appid = -1;
            int.TryParse(Request.QueryString["appid"].ToString(), out appid);

            Model.Orders.DocAttach[] attachs;
            bool upLoad = UpLoadFile(1, out attachs, Request.QueryString["appid"].ToString());
            if (upLoad)
            {
                //写库
                BLL.Orders.DocAttach bll = new BLL.Orders.DocAttach();
                bll.BatchAdd(attachs);
                if (appid == 33)
                {
                    ShowAttchList(appid, int.Parse(Request.QueryString["docid"].ToString()));
                }
                if (appid == 34)
                {
                    ShowImageAttchList(UploadObjectLiteral, appid, int.Parse(Request.QueryString["docid"].ToString()));
                }
            }
        }


        #endregion //End EventHandler

        #region Helper Methods

        private bool UpLoadFile(int userID, out Model.Orders.DocAttach[] attachs, string appid)
        {
            ///'遍历File表单元素
            HttpFileCollection files = HttpContext.Current.Request.Files;
            try
            {
                string[] arrExtension = ".jpg,.jpge,.bmp,.gif,.png,.tif".Split(',');
                if (appid == "33")
                {//上传文件
                    arrExtension = WebUtility.ReadConfig("UpDocAttachFileExtension").Split(new char[] { ',' });
                }
                List<Model.Orders.DocAttach> list = new List<Model.Orders.DocAttach>();
                for (int iFile = 0; iFile < files.Count; iFile++)
                {
                    ///'检查文件扩展名字
                    HttpPostedFile postedFile = files[iFile];
                    string fileName, fileExtension;
                    fileName = Server.HtmlEncode(System.IO.Path.GetFileName(postedFile.FileName));
                    int fileSize = files[iFile].ContentLength;
                    if (fileName != "")
                    {
                        fileExtension = System.IO.Path.GetExtension(fileName).ToLower();
                        
                        bool match = false;
                        for (int i = 0; i < arrExtension.Length; i++)
                        {
                            if (fileExtension == arrExtension[i])
                            {
                                match = true;
                                break;
                            }
                        }
                        if (!match)
                        {
                            this.lblMsg.Text = "您必须上传图片!";
                            attachs = new YaXing.Model.Orders.DocAttach[0];
                            return false;
                        }
                        BLL.Orders.AppManage bll = new BLL.Orders.AppManage();
                        Model.Orders.AppManage app = bll.GetModel(int.Parse(appid));

                        string saveDir = string.Format(@"AtthFiles\{0}\", app.AttachFolder);
                        string appPath = Request.PhysicalApplicationPath;
                        string newfileName = app.AttachFolder + "_" + YaXing.Common.Code.sRndNum(5) + fileExtension;
                        string savePath = appPath + saveDir + newfileName;
                        postedFile.SaveAs(savePath);
                        Model.Orders.DocAttach attach = new Model.Orders.DocAttach();
                        attach.AttachPath = newfileName;
                        attach.AttachFileName = fileName;
                        attach.AttachFileSize = fileSize;
                        attach.UpLoader = userID;
                        attach.UpLoadDate = DateTime.Now;
                        attach.DocID = int.Parse(Request.QueryString["docid"]);
                        attach.AppID = int.Parse(appid);
                        list.Add(attach);
                    }
                }
                if (list.Count > 0)
                    attachs = list.ToArray();
                else
                    attachs = new Model.Orders.DocAttach[0];
                return true;
            }
            catch (Exception ex)
            {
                this.lblMsg.Text = ex.Message;
                attachs = new Model.Orders.DocAttach[0];
                return false;
            }
        }

        protected void ShowImageAttchList(Literal targetLiteral, int appID, int docID)
        {
            BLL.Orders.AppManage bll = new BLL.Orders.AppManage();
            DataSet dsAttach = bll.GetAppInfo(docID, appID);

            if (dsAttach.Tables[0].Rows.Count == 0)
            {
                targetLiteral.Text = "无附件";
                return;
            }
            StringBuilder sb = new StringBuilder();
            string imgPath = Page.ResolveClientUrl("~/Images/");
            string attchPath = Page.ResolveClientUrl("~/AtthFiles/");
            string downPage = Page.ResolveClientUrl("~") + "FileDownLoad.aspx";

            sb.Append("<ol class=\"thumbnails\">");
            for (int i = 0; i < dsAttach.Tables[0].Rows.Count; i++)
            { //<li><img src='{0}File/{1}' alt='' />   <a href='{2}/{3}/{4}' target = '_blank' >{5}</a>   大小kb</li>
                sb.Append(string.Format("<li><img src='../atthfiles/{3}/{5}' width=\"240\" height=\"240\" alt='' /><br/><a href='{2}?fileFiled={3}&orgName={4}&realName={5}' target = '_blank'>{6}</a>   {7}KB  {8}</li>",
                    imgPath, //图标路径0
                    WebUtility.GetIco(System.IO.Path.GetExtension(dsAttach.Tables[0].Rows[i]["AttachFileName"].ToString()).ToLower()), //图标1
                    downPage, //到下载页面2
                    dsAttach.Tables[0].Rows[i]["AttachFolder"].ToString(),//在哪个文件夹中3                    
                    Server.UrlEncode(dsAttach.Tables[0].Rows[i]["AttachFileName"].ToString()), //中文名4
                    dsAttach.Tables[0].Rows[i]["AttachPath"].ToString(), //实际文件名5
                    dsAttach.Tables[0].Rows[i]["AttachFileName"].ToString(), //中文名6
                    (Convert.ToInt32(dsAttach.Tables[0].Rows[i]["AttachFileSize"]) / 1024).ToString(),//7
                    string.Format("<a href='#' onclick='removeAttach({0},this)'><img src='../images/delete01.gif' alt='点击可以删除此附件' style='border:0;' /></a>", dsAttach.Tables[0].Rows[i]["aid"])
                    ));
            }
            sb.Append("</ol>");
            targetLiteral.Text = sb.ToString();
        }

        #endregion //End Helper Methods



        protected void ShowAttchList(int appID, int docID)
        {
            BLL.Orders.AppManage bll = new BLL.Orders.AppManage();
            DataSet dsAttach = bll.GetAppInfo(docID, appID);

            if (dsAttach.Tables[0].Rows.Count == 0)
            {
                this.UploadObjectLiteral.Text = "无附件";
                return;
            }
            StringBuilder sb = new StringBuilder();
            string imgPath = Page.ResolveClientUrl("~/Images/");
            string attchPath = Page.ResolveClientUrl("~/AtthFiles/");
            string downPage = Page.ResolveClientUrl("~") + "FileDownLoad.aspx";

            sb.Append("<ol>");
            for (int i = 0; i < dsAttach.Tables[0].Rows.Count; i++)
            { //<li><img src='{0}File/{1}' alt='' />   <a href='{2}/{3}/{4}' target = '_blank' >{5}</a>   大小kb</li>
                sb.Append(string.Format("<li><img src='{0}File/{1}' alt='' />   <a href='{2}?fileFiled={3}&orgName={4}&realName={5}' target = '_blank'>{6}</a>   {7}KB  {8}</li>",
                    imgPath, //图标路径0
                    WebUtility.GetIco(System.IO.Path.GetExtension(dsAttach.Tables[0].Rows[i]["AttachFileName"].ToString()).ToLower()), //图标1
                    downPage, //到下载页面2
                    dsAttach.Tables[0].Rows[i]["AttachFolder"].ToString(),//在哪个文件夹中3                    
                    Server.UrlEncode(dsAttach.Tables[0].Rows[i]["AttachFileName"].ToString()), //中文名4
                    dsAttach.Tables[0].Rows[i]["AttachPath"].ToString(), //实际文件名5
                    dsAttach.Tables[0].Rows[i]["AttachFileName"].ToString(), //中文名6
                    (Convert.ToInt32(dsAttach.Tables[0].Rows[i]["AttachFileSize"]) / 1024).ToString(),//7
                    string.Format("<a href='#' onclick='removeAttach({0},this)'><img src='../images/delete01.gif' alt='点击可以删除此附件' style='border:0;' /></a>", dsAttach.Tables[0].Rows[i]["aid"])
                    ));
            }
            sb.Append("</ol>");
            this.UploadObjectLiteral.Text = sb.ToString();
        }

        
    }

举报

相关推荐

Vue<自定义表单校验>

0 条评论