知识在于积累(.NET之路……)

导航

FineUIPro.Grid与jquery上传插件uploadifive混合使用办法

一、效果图:

 

二、实现

 主要实现的目标是将上传插件放到fineuipro.grid的一列中,并实现上传功能。

1、aspx页:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="aqjg_xckh_edit.aspx.cs" Inherits="xcjd.aqjg_xckh_edit" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>
    <link href="/bootstrap/css/bootstrap.min.css" rel="stylesheet" />
    <link href="/css/font-awesome.min.css" rel="stylesheet" />
    <link href="/css/animate.min.css" rel="stylesheet">
    <link href="/css/style.min.css" rel="stylesheet">
    <script src="/js/jquery-2.1.4.min.js"></script>
    <link href="/uploadifive/uploadifive.css" rel="stylesheet" type="text/css" />
    <!--[if lt IE 9]>
        <script src="/js/html5shiv.js"></script>
        <script src="/js/respond.min.js"></script>
    <![endif]-->
    <style>
        .f-panel-body .f-field {
            margin-bottom: 0px;
            width: 100%;
        }

        .f-inline-block {
            width: 100%;
        }

        .table > tbody > tr > td, .table > tbody > tr > th, .table > tfoot > tr > td, .table > tfoot > tr > th, .table > thead > tr > td, .table > thead > tr > th {
            border-color: #d9f1fe;
        }

        .table-bordered > tbody > tr > td, .table-bordered > tbody > tr > th, .table-bordered > tfoot > tr > td, .table-bordered > tfoot > tr > th, .table-bordered > thead > tr > td, .table-bordered > thead > tr > th {
            border-color: #b9e1f6;
        }

        .f-grid-cell.f-grid-cell-contents .f-grid-cell-inner {
            white-space: normal;
            word-break: break-all;
        }
        .f-grid-cell.f-grid-cell-atta .f-grid-cell-inner {
            white-space: normal;
            word-break: break-all;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">

        <f:PageManager AutoSizePanelID="panel1" ID="PageManager1" FormOffsetRight="0px"
            runat="server">
        </f:PageManager>
        <f:Panel runat="server" ID="panel1" ShowBorder="false" ShowHeader="false" BodyPadding="0" Layout="Fit">
            <Toolbars>
                <f:Toolbar ID="ToolbarTop" runat="server">
                    <Items>
                        <f:Button ID="btnClose" runat="server" Text="关闭" Icon="SystemClose" ToolTip="放弃当前修改,并关闭窗口"
                            ToolTipType="title" EnablePostBack="false">
                        </f:Button>
                        <f:Button ID="btnSaveClose" runat="server" Text="保存" Icon="SystemSave" ToolTip="保存当前数据并刷新列表"
                            ToolTipType="Title" OnClick="btnSaveClose_Click">
                        </f:Button>
                        <f:ToolbarFill ID="ToolbarFill1" runat="server">
                        </f:ToolbarFill>
                    </Items>
                </f:Toolbar>
            </Toolbars>
            <Items>
                <f:ContentPanel runat="server" ShowBorder="false" ShowHeader="false" BodyPadding="0" AutoScroll="true">
                    <div class="gray-bg">
                        <div class="wrapper wrapper-content  animated fadeInRight article">
                            <div class="row">
                                <div class="col-lg-10 col-lg-offset-1">
                                    <div class="ibox">
                                        <div class="ibox-content">
                                            <div class="text-center article-title" style="margin: 0px 0px 40px">
                                                <h2>现场考核表
                                                </h2>
                                            </div>                                            
                                            <f:Grid ID="Grid1" ShowBorder="true" ShowHeader="false"
                                                runat="server" DataKeyNames="itype,contents,ScoreStd,unit,id"
                                                BodyPadding="0px" EnableHeaderMenu="false" EnableColumnLines="true">
                                                <Toolbars>
                                                    <f:Toolbar ID="Toolbar1" runat="server">
                                                        <Items>
                                                            <f:ToolbarText runat="server" ID="ToolbarText1" Text="注:得分填正数,如:1、2、3 等;扣分填负数,如:-1、-2、-3 等" CssStyle="color:red;"></f:ToolbarText>
                                                        </Items>
                                                    </f:Toolbar>
                                                </Toolbars>
                                                <Columns>
                                                    <f:RowNumberField />
                                                    <f:BoundField Width="200px" DataField="itype" HeaderText="考核类别" TextAlign="center" />
                                                    <f:BoundField ColumnID="contents" MinWidth="200px" ExpandUnusedSpace="true" DataField="contents" DataToolTipField="contents" HeaderText="达标要求" HeaderTextAlign="Center" HtmlEncode="false" />
                                                    <f:BoundField Width="80px" DataToolTipField="scoreStd" DataField="scoreStd"
                                                        HeaderText="考核分数" HeaderTextAlign="center" TextAlign="Center" DataFormatString="{0:#.#}" />
                                                    <f:TemplateField HeaderText="得分" EnableColumnHide="false" Width="80px" TextAlign="Center">
                                                        <ItemTemplate>
                                                            <asp:TextBox runat="server" Width="98%" ID="tbxScore" Style="text-align: center;"
                                                                TabIndex='<%# Container.DataItemIndex + 10 %>' Text='<%#string.Format("{0:#.#}", Eval("score")) %>'></asp:TextBox>
                                                        </ItemTemplate>
                                                    </f:TemplateField>
                                                    <f:TemplateField ColumnID="atta" HeaderText="附件" EnableColumnHide="false" Width="300px" HeaderTextAlign="Center">
                                                        <ItemTemplate>
                                                            <div>
                                                                <input type="file" name="uploadifive" id="uploadifive_<%# Container.DataItemIndex%>" />
                                                                <div id="uploadifive_Atta">
                                                                </div>
                                                                <div class="attach-name">
                                                                    <%#Webpub.Comm.GetAttaHtmlByids(Eval("atta_ids").ToString(),false)%>
                                                                </div>
                                                                <asp:HiddenField runat="server" ID="hid_atta_ids" Value='<%#Eval("atta_ids")%>' />
                                                            </div>
                                                        </ItemTemplate>
                                                    </f:TemplateField>
                                                </Columns>
                                            </f:Grid>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </f:ContentPanel>
            </Items>
        </f:Panel>
    </form>
</body>
</html>
<script src="/js/plugins/layer/layer.min.js"></script>
<script src="/uploadifive/jquery.uploadifive.min.js" type="text/javascript"></script>
<script type="text/javascript">
    String.prototype.trimStart = function (trimStr) {
        if (!trimStr) { return this; }
        var temp = this;
        while (true) {
            if (temp.substr(0, trimStr.length) != trimStr) {
                break;
            }
            temp = temp.substr(trimStr.length);
        }
        return temp;
    };
    String.prototype.trimEnd = function (trimStr) {
        if (!trimStr) { return this; }
        var temp = this;
        while (true) {
            if (temp.substr(temp.length - trimStr.length, trimStr.length) != trimStr) {
                break;
            }
            temp = temp.substr(0, temp.length - trimStr.length);
        }
        return temp;
    };
    String.prototype.trim = function (trimStr) {
        var temp = trimStr;
        if (!trimStr) { temp = " "; }
        return this.trimStart(temp).trimEnd(temp);
    };

    F.ready(function () {
        $('[name="uploadifive"]').each(function () {
            //debugger;
            initUploadifive($(this));

            //删除附件
            $(document).on('click', '.attach-name a.delete', function () {
                var atta = $(this).parent();
                var hid_atta_ids = $(this).parent().parent().parent().find('[type="hidden"]');
                //询问框
                var index = layer.confirm('确定删除当前附件?', {
                    btn: ['确定', '取消'] //按钮
                }, function () {
                    layer.close(index);
                    //debugger;
                    var atta_ids = "," + hid_atta_ids.val() + ",";
                    if (atta_ids != "")
                        atta_ids = atta_ids.replace("," + atta.attr("data-id") + ",", ",");

                    hid_atta_ids.val(atta_ids.trim(','));

                    atta.remove();
                }, function () {
                });

            });

        });


    });
    function initUploadifive(ctrl) {
        //debugger;
        var ctrl_p = ctrl.parent();
        ctrl.uploadifive({
            auto: true,
            buttonText: '<span class="fa fa-folder-open"></span> 浏览',
            width: '60px',
            height: '22',
            uploadScript: 'AjaxHandle/UploadifiveUploadServer.ashx',
            formData: { },
            uploadLimit: 50,
            multi: true,
            dropTarget: ctrl_p.attr('id'),
            'removeCompleted': true,
            'onUploadError': function (file, errorCode, errorMsg, errorString) {
                //debugger;
                alert('上传失败');
            },
            'onUploadComplete': function (file, data, response) {
                //debugger;
                var json = eval('(' + data + ')');
                ctrl.uploadifive('cancel', file);
                if (json.code == "200") {
                    var span = '<div class="file_item" data-id="' + json.id + '" data-path="' + json.file_path + '"><i class="fa fa-file-o"></i> ' + file.name + '  <a href="/AttaDownLoad.aspx?p=' + escape(json.file_path) + '">[下载]</a>  <a href="/AttaView.aspx?p=' + escape(json.file_path) + '" target="_blank">[查看]</a>  <a href="javascript:void(0);" class="delete">[删除]</a></div>';
                    ctrl_p.find('div.attach-name').append(span);

                    var atta_ids = ctrl_p.find('[type="hidden"]').val();
                    if (atta_ids != "")
                        atta_ids += "," + json.id;
                    else
                        atta_ids = json.id;

                    ctrl_p.find('[type="hidden"]').val(atta_ids);


                }
            }
        });
    }

</script>
View Code

 

2、aspx.cs页:主要是保存的时候,获取上传的附件id

//遍历Grid
for (int i = 0; i < Grid1.Rows.Count; i++)
                        {
                            

                            System.Web.UI.WebControls.HiddenField hid_atta_ids = (System.Web.UI.WebControls.HiddenField)row.FindControl("hid_atta_ids");
                            atta_ids = hid_atta_ids.Value.Trim(',');
}
View Code

3、上传文件的处理代码:UploadifiveUploadServer.ashx

HttpContext RequestStr = null;
        public void ProcessRequest(HttpContext context)
        {
            RequestStr = context;
            RequestStr.Response.ContentType = "text/plain";
            RequestStr.Response.Charset = "utf-8";

            string path = "~/upload/" + DateTime.Today.Year.ToString() + "/" + DateTime.Today.Month.ToString();
            //if (RequestStr.Request["path"] != null)
            //    path = "~/upload/" + HttpUtility.UrlDecode(RequestStr.Request["path"]).TrimStart('/');

            if (RequestStr.Request.Files.Count > 0)
            {
                HttpPostedFile file = RequestStr.Request.Files[0];
                string newname = file.FileName.Substring(file.FileName.LastIndexOf('\\') + 1);

                string fileName = file.FileName;
                string ext = fileName.Substring(fileName.LastIndexOf('.'));
                string size = (file.ContentLength / (1024 * 1024)).ToString() + "MB";

                if (!Directory.Exists(RequestStr.Server.MapPath(path)))
                    Directory.CreateDirectory(RequestStr.Server.MapPath(path));

                fileName = fileName.Replace(":", "_").Replace(" ", "_").Replace("\\", "_").Replace("/", "_");
                fileName = DateTime.Now.Ticks.ToString() + "_" + newname;

                file.SaveAs(RequestStr.Server.MapPath(path.TrimEnd('/') + "/" + fileName));

                #region 保存到数据库
                StringBuilder strSql = new StringBuilder();
                strSql.Append("insert into tb_Attachment(");
                strSql.Append("[name],[paths],[ext],[size],[creator],[addTime])");
                strSql.Append(" values (");
                strSql.Append("@name,@paths,@ext,@size,@creator,@addTime)");
                strSql.Append(";select @@IDENTITY");
                SqlParameter[] parameters = {
                            new SqlParameter("@name", SqlDbType.VarChar,100),
                            new SqlParameter("@paths", SqlDbType.VarChar,500),
                            new SqlParameter("@ext", SqlDbType.VarChar,50),
                            new SqlParameter("@size", SqlDbType.VarChar,50),
                            new SqlParameter("@creator", SqlDbType.VarChar,50),
                            new SqlParameter("@addTime", SqlDbType.DateTime)};
                parameters[0].Value = newname;
                parameters[1].Value = path.TrimEnd('/') + "/" + fileName;
                parameters[2].Value = ext;
                parameters[3].Value = size;
                parameters[4].Value = ((pubSession)HttpContext.Current.Session["pubSession"]).UserName;
                parameters[5].Value = DateTime.Now;

                object obj = gxjt.DBUtility.DbHelperSQL.GetSingle(strSql.ToString(), parameters);

                #endregion

                if (obj != null)
                {
                    RequestStr.Response.Write("{\"code\":\"200\",\"id\":\"" + obj.ToString() + "\",\"file_name\":\"" + newname + "\",\"file_path\":\"" + path.TrimEnd('/') + "/" + fileName + "\"}");
                }
                else
                {
                    RequestStr.Response.Write("{\"code\":\"300\"}");
                }
            }

            RequestStr.Response.End();
        }
View Code

 

posted on 2016-07-07 11:37  汤尼  阅读(406)  评论(0编辑  收藏  举报