异步上传文件

第三方异步上传MyAjaxForm下载地址: http://jquery.malsup.com/form/#download

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>权限管理</title>
    <link href="~/Content/themes/default/easyui.css" rel="stylesheet" />
    <link href="~/Content/themes/icon.css" rel="stylesheet" />
    <script src="~/Scripts/jquery-1.7.1.min.js"></script>
    <script src="~/Scripts/jquery.easyui.min.js"></script>
    <script src="~/Scripts/easyui-lang-zh_CN.js"></script>
    <script src="~/Scripts/datapattern.js"></script>
    <script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
    <script src="~/Scripts/MyAjaxForm.js"></script>
    <script type="text/javascript">
        $(function () {
            loadData();
            $("#addDiv").css("display", "none");
            $("#editDiv").css("display", "none");
            $("#setActionRoleDiv").css("display", "none");
            bindActionTypeEnumChange();
            bindFileUpClick();
        });
        //给权限类别绑定change事件
        function bindActionTypeEnumChange() {
            $("#ActionTypeEnumChange").change(function () {
                if ($(this).val() == "1") {
                    $("#actionIconTr").fadeIn("show");
                } else {
                    $("#actionIconTr").fadeOut("show");
                }

            })
        }
        //文件上传
        function bindFileUpClick() {
            $("#btnFileUp").click(function () {
                if ($("#fileUp").val() == "") {
                    $.messager.alert("提示", "请选择上传的文件", "error");
                    return;
                }
                //开始进行异步上传图片文件
                $("#addForm").ajaxSubmit({
                    success: function (data) {
                        var serverData = data.split(':');
                        if (serverData[0] == "yes") {
                            $("#showImage").append("<img src='" + serverData[1] + "' width='40px' height='40px'/>");
                            $("#hiddenMenuIcon").val(serverData[1]);//将上传成功的图片地址放在隐藏域中,单击提交表单按钮,完成提交
                        } else {
                            $.messager.alert("提示",serverData[1],"error");
                        }
                    },
                    url: "/ActionInfo/FileUpload",
                    type: "post"

                });
            });
        }

        function loadData(pars) {
            $('#tt').datagrid({
                url: '/ActionInfo/GetActionInfo',
                title: '权限数据表格',
                 700,
                height: 400,
                fitColumns: true, //列自适应
                nowrap: false,
                idField: 'ID',//主键列的列明
                loadMsg: '正在加载权限的信息...',
                pagination: true,//是否有分页
                singleSelect: false,//是否单行选择
                pageSize: 5,//页大小,一页多少条数据
                pageNumber: 1,//当前页,默认的
                pageList: [5, 10, 15],
                queryParams: pars,//往后台传递参数
                columns: [[//c.UserName, c.UserPass, c.Email, c.RegTime
                    { field: 'ck', checkbox: true, align: 'left',  50 },
                    { field: 'ID', title: '编号',  80 },
                    { field: 'ActionInfoName', title: '权限名称',  120 },
                    { field: 'Url', title: '请求地址',  120 },
                     { field: 'HttpMethod', title: '请求方式',  120 },
                      {
                          field: 'ActionTypeEnum', title: '权限类型',  120,
                          formatter: function (value, row, index) {
                              if (value == "1") {
                                  return "菜单权限";
                              } else {
                                  return "普通权限";
                              }
                          }
                      },
                     { field: 'Sort', title: '排序',  120 },
                      { field: 'Remark', title: '备注',  120 },
                    {
                        field: 'SubTime', title: '时间',  80, align: 'right',
                        formatter: function (value, row, index) {
                            return (eval(value.replace(//Date((d+))//gi, "new Date($1)"))).pattern("yyyy-M-d");
                        }
                    },
                    {
                        field: 'Operator', title: '操作',  120,
                        formatter: function (value, row, index) {
                            var str = "<a href='javascript:void(0)' ids='" + row.ID + "' class='deletes'>删除</a>";
                            str = str + "&nbsp;&nbsp;<a href='javascript:void(0)' ids='" + row.ID + "' class='edits'> 编辑</a>";
                            return str;
                        }
                    }
                ]],
                toolbar: [{
                    id: 'btnDelete',
                    text: '删除',
                    iconCls: 'icon-remove',
                    handler: function () {

                        deleteInfo();
                    }
                }, {
                    id: 'btnAdd',
                    text: '添加',
                    iconCls: 'icon-add',
                    handler: function () {

                        addInfo();
                    }
                }, {
                    id: 'btnEdit',
                    text: '编辑',
                    iconCls: 'icon-edit',
                    handler: function () {

                        eidtInfo();
                    }
                }, {
                    id: 'btnSetActionRole',
                    text: '为权限分配角色',
                    iconCls: 'icon-edit',
                    handler: function () {

                        setActionRoleInfo();
                    }
                }],
                onLoadSuccess: function () {
                    $(".deletes").click(function () {
                        alert($(this).attr("ids"));
                    });
                }

            });
        }
        //为权限分配角色
        function setActionRoleInfo() {
            var rows = $('#tt').datagrid('getSelections');
            if (rows.length != 1) {
                //alert("请选择要修改的商品!");
                $.messager.alert("提醒", "请选择要分配角色的权限1条记录!", "error");
                return;
            }
            $("#setActionRoleFrame").attr("src", "/ActionInfo/SetActionRole/?id=" + rows[0].ID);
            $("#setActionRoleDiv").css("display", "block");
            $('#setActionRoleDiv').dialog({
                title: "为权限分配角色信息",
                 300,
                height: 350,
                collapsible: true,
                resizable: true,
                modal: true,
                buttons: [{
                    text: '确定',
                    iconCls: 'icon-ok',
                    handler: function () {
                        //$("#editForm").submit();//提交表单
                        var childWindow = $("#setActionRoleFrame")[0].contentWindow;//获取子窗体的window对象.
                        childWindow.subForm();
                    }
                }, {
                    text: '取消',
                    handler: function () {
                        $('#setActionRoleDiv').dialog('close');
                    }
                }]
            });

        }
        //为权限分配完成角色以后调用该方法
        function setActionRoleAfter(data) {
            if (data == "ok") {
                $('#setActionRoleDiv').dialog('close');
            } else {
                $.messager.alert("提示","分配异常!!","error");
            }
        }

        //编辑用户信息
        function eidtInfo() {
            var rows = $('#tt').datagrid('getSelections');
            if (rows.length != 1) {
                //alert("请选择要修改的商品!");
                $.messager.alert("提醒", "请选择要编辑的1条记录!", "error");
                return;
            }
            // $.post("/UserInfo/GetUserInfoModel", { "id": rows[0].ID }, function (data) {
            //if (data.msg == "ok") {
            //$("#txtUName").val(data.serverData.UName);
            //$("#txtUPwd").val(data.serverData.UPwd);
            //$("#txtRemark").val(data.serverData.Remark);
            //$("#txtSort").val(data.serverData.Sort);
            //$("#txtSubTime").val(ChangeDateFormat(data.serverData.SubTime));
            //$("#txtDelFlag").val(data.serverData.DelFlag);
            //$("#txtId").val(data.serverData.ID);
            $("#editFrame").attr("src", "/RoleInfo/ShowEditInfo/?id=" + rows[0].ID);
            $("#editDiv").css("display", "block");

            $('#editDiv').dialog({
                title: "编辑角色信息",
                 300,
                height: 350,
                collapsible: true,
                resizable: true,
                modal: true,
                buttons: [{
                    text: '确定',
                    iconCls: 'icon-ok',
                    handler: function () {
                        //$("#editForm").submit();//提交表单
                        var childWindow = $("#editFrame")[0].contentWindow;//获取子窗体的window对象.
                        childWindow.subForm();
                    }
                }, {
                    text: '取消',
                    handler: function () {
                        $('#editDiv').dialog('close');
                    }
                }]
            });


        }
        //修改完成以后调用该方法
        function afterEdit(data) {
            if (data == "ok") {
                $('#editDiv').dialog('close');
                $('#tt').datagrid('reload');
            } else {
                $.messager.alert("提醒", "修改数据错误!!", "error");
            }
        }


        //添加信息
        function addInfo() {
            $("#addDiv").css("display", "block");
            $('#addDiv').dialog({
                title: "添加权限信息",
                 400,
                height: 400,
                collapsible: true,
                resizable: true,
                modal: true,
                buttons: [{
                    text: '确定',
                    iconCls: 'icon-ok',
                    handler: function () {
                        $("#addForm").submit();//提交表单
                    }
                }, {
                    text: '取消',
                    handler: function () {
                        $('#addDiv').dialog('close');
                    }
                }]
            });

        }
        //添加完成以后调用该方法
        function afterAdd(data) {
            if (data == "ok") {
                $("#addForm input").val("");
                $('#addDiv').dialog('close');
                $('#tt').datagrid('reload');
            } else {
                $.messager.alert("提示", "添加失败", "error");
            }
        }
        //删除用户数据
        function deleteInfo() {
            var rows = $('#tt').datagrid('getSelections');
            if (!rows || rows.length == 0) {
                //alert("请选择要修改的商品!");
                $.messager.alert("提醒", "请选择要删除的记录!", "error");
                return;
            }
            $.messager.confirm("提示", "确定要删除该记录?", function (r) {
                if (r) {
                    var strId = "";
                    for (var i = 0; i < rows.length; i++) {
                        strId = strId + rows[i].ID + ",";//1,2,3,
                    }
                    strId = strId.substr(0, strId.length - 1);
                    $.post("/ActionInfo/DeleteActionInfo", { "strId": strId }, function (data) {
                        if (data == "ok") {
                            $('#tt').datagrid('clearSelections');
                            $('#tt').datagrid('reload');
                            //loadData();
                        } else {
                            $.messager.alert("提醒", "删除的记录失败!", "error");
                        }
                    });
                }
            });
        }

        //将序列化成json格式后日期(毫秒数)转成日期格式
        function ChangeDateFormat(cellval) {
            var date = new Date(parseInt(cellval.replace("/Date(", "").replace(")/", ""), 10));
            var month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
            var currentDate = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
            return date.getFullYear() + "-" + month + "-" + currentDate;
        }
    </script>
</head>
<body>
    <div>

        <table id="tt" style=" 700px;" title="标题,可以使用代码进行初始化,也可以使用这种属性的方式" iconcls="icon-edit">
        </table>
    </div>
    <!---------------添加权限信息--------------------->
    <div id="addDiv">
        @using (Ajax.BeginForm("AddActionInfo", "ActionInfo", new { }, new AjaxOptions() { HttpMethod = "post", OnSuccess = "afterAdd" }, new { id = "addForm" }))
        {
            <table>
                <tr>
                    <td>权限名称</td>
                    <td>
                        <input type="text" name="ActionInfoName" /></td>
                </tr>

                 <tr>
                    <td>Url</td>
                    <td>
                        <input type="text" name="Url" /></td>
                </tr>

                 <tr>
                    <td>HttpMethod</td>
                    <td>
                    <select name="HttpMethod">
                        <option value="GET">GET</option>
                         <option value="POST">POST</option>
                    </select>   
                    
                    </td>
                </tr>

                   <tr>
                    <td>权限类型</td>
                    <td>
                    <select name="ActionTypeEnum" id="ActionTypeEnumChange">
                        <option value="0">普通权限</option>
                         <option value="1">菜单权限</option>
                    </select>   
                    
                    </td>
                </tr>

                <tr style="display:none" id="actionIconTr">
                    <td>菜单图标</td>
                    <td><input type="file" name="fileIconUp" id="fileUp" />
                    <input type="button" value="上传图片" id="btnFileUp" />
                        <input type="hidden" name="MenuIcon" id="hiddenMenuIcon" />
                    <div id="showImage"></div></td>
                </tr>



                <tr>
                    <td>排序</td>
                    <td>
                        <input type="text" name="Sort" /></td>
                </tr>
                <tr>
                    <td>备注</td>
                    <td>
                        <input type="text" name="Remark" /></td>
                </tr>


            </table>
        }
    </div>
    <!---------------添加权限信息结束--------------------->


    <!---------------修改用户信息--------------------->
    <div id="editDiv">
        <iframe id="editFrame" scrolling="no" width="100%" height="100%" frameborder="0"></iframe>
        @* @using(Ajax.BeginForm("EditUserInfo", "UserInfo", new { }, new AjaxOptions() {HttpMethod="post", OnSuccess="afterEdit"}, new {id="editForm"})){
            <input type="hidden" name="SubTime" id="txtSubTime" />
            <input type="hidden" name="DelFlag" id="txtDelFlag" />
            <input type="hidden" name="ID" id="txtId" />
        <table>
            <tr><td>用户名</td><td><input type="text" name="UName" id="txtUName" /></td></tr>
             <tr><td>密码</td><td><input type="text" name="UPwd" id="txtUPwd" /></td></tr>
             <tr><td>备注</td><td><input type="text" name="Remark" id="txtRemark" /></td></tr>
             <tr><td>排序</td><td><input type="text" name="Sort" id="txtSort" /></td></tr>

        </table>
        }*@
    </div>

    <!---------------修改用户信息结束--------------------->

    <div id="setActionRoleDiv">
        <iframe id="setActionRoleFrame" scrolling="no" frameborder="0" width="100%" height="100%"></iframe>
    </div>

</body>
</html>
View Code
using CZBK.ItcastOA.Model;
using CZBK.ItcastOA.Model.Enum;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace CZBK.ItcastOA.WebApp.Controllers
{
    public class ActionInfoController : BaseController
    {
        //
        // GET: /ActionInfo/
        IBLL.IActionInfoService ActionInfoService { get; set; }
        IBLL.IRoleInfoService RoleInfoService { get; set; }
        public ActionResult Index()
        {
            return View();
        }
        #region 获取权限信息
        public ActionResult GetActionInfo()
        {
            int pageIndex = Request["page"] != null ? int.Parse(Request["page"]) : 1;
            int pageSize = Request["rows"] != null ? int.Parse(Request["rows"]) : 5;
            int totalCount;
            short delFlag = (short)DelFlagEnum.Normarl;
           var actionInfoList=ActionInfoService.LoadPageEntities<int>(pageIndex,pageSize,out totalCount,a=>a.DelFlag==delFlag,a=>a.ID,true);
           var temp = from a in actionInfoList
                      select new {
                      ID=a.ID,
                      ActionInfoName = a.ActionInfoName,
                      Sort=a.Sort,
                      Remark=a.Remark,
                      Url=a.Url,
                      HttpMethod=a.HttpMethod,
                      ActionTypeEnum=a.ActionTypeEnum,
                      SubTime=a.SubTime
                      };
           return Json(new { rows = temp, total = totalCount }, JsonRequestBehavior.AllowGet);
        }
        #endregion

        #region 获取上传的图片
        public ActionResult FileUpload()
        {
            HttpPostedFileBase file=Request.Files["fileIconUp"];
            if (file != null)
            {
                string fileName = Path.GetFileName(file.FileName);//获取上传的文件名
                string fileExt = Path.GetExtension(fileName);//获取扩展名
                if (fileExt == ".jpg")
                {
                    string dir = "/MenuIcon/"+DateTime.Now.Year+"/"+DateTime.Now.Month+"/"+DateTime.Now.Day+"/";
                    Directory.CreateDirectory(Path.GetDirectoryName(Request.MapPath(dir)));
                    string filenewName = Guid.NewGuid().ToString();
                    string fullDir = dir + filenewName + fileExt;
                    file.SaveAs(Request.MapPath(fullDir));
                    return Content("yes:"+fullDir);
                }
                else
                {
                    return Content("no:文件类型错误!!");
                }
            }
            else
            {
                return Content("no:请选择上传的图片文件");
            }
        }
        #endregion

        #region 完成权限的添加
        public ActionResult AddActionInfo(ActionInfo actionInfo)
        {
            actionInfo.DelFlag = 0;
            actionInfo.ModifiedOn = DateTime.Now.ToShortTimeString();
            actionInfo.SubTime = DateTime.Now;
            actionInfo.Url = actionInfo.Url.ToLower();
            ActionInfoService.AddEntity(actionInfo);
            return Content("ok");
        }

        #endregion

        #region 为权限分配角色
        public ActionResult SetActionRole()
        {
            int id = int.Parse(Request["id"]);//要分配角色的权限的编号
           var actionInfo= ActionInfoService.LoadEntities(a=>a.ID==id).FirstOrDefault();
           ViewBag.ActionInfo = actionInfo;
            //获取所有的角色.
            short delflag=(short)DelFlagEnum.Normarl;
           var AllRoleList = RoleInfoService.LoadEntities(a=>a.DelFlag==delflag).ToList();
            //获取当前的权限已经有的角色信息.
           var AllExtRoleIdList = (from r in actionInfo.RoleInfo
                                   select r.ID).ToList();
           ViewBag.RoleList = AllRoleList;
           ViewBag.RoleIdList = AllExtRoleIdList;
           return View();

        }
        /// <summary>
        /// 完成对权限的角色分配
        /// </summary>
        /// <returns></returns>
        public ActionResult SetActionRoleInfo()
        {
            int actionId = int.Parse(Request["actionId"]);
            List<int> list = new List<int>();
            string[] AllKeys = Request.Form.AllKeys;//获取所有的表单中的name属性的值.
            foreach (string key in AllKeys)
            {
                if (key.StartsWith("cba_"))
                {
                    string k = key.Replace("cba_","");
                    list.Add(int.Parse(k));
                }
            }
            if (ActionInfoService.SetActionRoleInfo(actionId, list))
            {
                return Content("ok");
            }
            else
            {
                return Content("no");
            }

        }
        #endregion
      
    }
}
View Code
原文地址:https://www.cnblogs.com/ecollab/p/6170774.html