.net MVC5+EF6+bootstrap搭建框架,从入门到精通(五)——之ajax提交表单回传ID然后根据ID实现图片上传

.net MVC5+EF6+bootstrap搭建框架,从入门到精通(五)——之ajax提交表单回传ID然后根据ID实现图片上传

前言废话

人生最美不过遇见,最长情的告白不过是陪伴,最怂的大概就是很喜欢一个女孩却不敢表白,幸与不幸的是她永远看不到我这个博客,绝望的zzk,浴火重生zzk,不死鸟zzk,万里独行zzk,其实都是一个zzk,不过是神的恩威,人的四面而已

直接上代码

.cshtml前台html核心代码,我在里面都写了注解


@using (Ajax.BeginForm("AddEditAjax", "Home", null,
      new AjaxOptions
      {
          HttpMethod = "Post",
          Confirm = "确定吗?",
          OnBegin = "onbegin",
          OnComplete = "oncomplete",
          OnFailure = "onfailure",
          OnSuccess = "onsuccess"
      }))
{
    @Html.AntiForgeryToken()
    
<div class="form-horizontal">
    <h4>tb_staff</h4>
    <hr />
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    <div class="form-group">
        @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.Sex, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Sex, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Sex, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.Age, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Age, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Age, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.Phone, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Phone, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Phone, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.Salary, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Salary, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Salary, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.Nationality, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Nationality, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Nationality, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        <label class="col-sm-2 control-label">图片上传:</label>
        <div class="col-sm-4">
            <input id="fileUpload" name="myfile" type="file" data-show-caption="true" multiple="multiple">
            <p class="help-block">支持jpg、jpeg、png格式,大小不超过2.0M</p>
        </div>
    </div>

    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Create" class="btn btn-default" />
        </div>
    </div>
</div>
}

后台controller新增数据并返回ID


        public ActionResult AddEditAjax()
        {
            string json = string.Empty;
            var Name = Request["Name"];
            var Sex = Request["Sex"];
            var Age = Request["Age"];
            var Phone = Request["Phone"];
            var Salary = Request["Salary"];
            var Nationality = Request["Nationality"];
            if (Name != "" && Name != null)
            {
                //新增测试:
                tb_staff model = new tb_staff()
                {
                    Name = Name,
                    Sex = Convert.ToBoolean(Sex),
                    Age = Convert.ToInt32(Age),
                    Phone = Phone,
                    Salary = (float)Convert.ToDouble(Salary),
                    Nationality = Nationality
                };
                cbll.Add(model);
                cbll.SaveChanges();
                //获取当前上传数据的自增列用于后面数据的处理
                int iiiid = model.Id;
                //此处数据偷懒了,哈哈
                json = "[{\"error\":\""+iiiid.ToString()+"\"}]";
            }
            else
            {
                json = "[{\"error\":\"0\"}]";
            }
            return Content(json);
        }

根据上面控制器的方法返回的数据触发fileinput的上传事件

<script type="text/javascript">
    var commId;
    //页面加载
    $(function () {
    //图片上传的后台方法
        var path = "/Home/UploadFile";
        //调用Fileinput控件参数初始化数据
        initFileInput("fileUpload", path);

    })
    function initFileInput(ctrlName, uploadUrl) {
        var control = $('#' + ctrlName);
        control.fileinput({
            language: 'zh', //设置语言
            uploadUrl: uploadUrl,  //上传地址
            minFileCount: 0,
            uploadAsync: true,
            showUpload: false,//是否显示上传按钮 
            showRemove: false,//是否显示删除按钮 
            showCaption: false,//是否显示输入框 
            maxFileCount: 2,
            enctype: 'multipart/form-data',
            maxFileSize: 5120,//限制上传大小KB
            overwriteInitial: true,//不覆盖已上传的图片
            allowedPreviewTypes: ['image', 'html', 'text', 'video', 'audio', 'flash', 'object'],
            allowedFileExtensions: ['jpg', 'png', 'gif', 'txt', 'xls'],//可以可选择的违建格式
            //下面四个配置加载图片
            initialPreviewAsData: true,
            initialPreviewFileType: 'image',
            //initialPreview: ["../attachmenti/20200322035303.png","../attachmenti/20200322035259.jpg"], //要显示的图片的路径  
            //initialPreviewConfig: [{caption:"20200322035303", filename: "20200322035303", downloadUrl:"C:/Users/PC/source/repos/zzkMvc/zzkMvc.UII/attachmenti/20200322035303.png", key:"1"},{caption:"20200322035259", filename: "20200322035259", downloadUrl:"C:/Users/PC/source/repos/zzkMvc/zzkMvc.UII/attachmenti/20200322035259.jpg", key:"1"}], 
            // elErrorContainer: '#kv-error-1',//错误显示的文本continner
            showBrowse: true,
            msgFilesTooMany: "选择上传的文件数量({n}) 超过允许的最大数值{m}!",
            browseOnZoneClick: true,
            ajaxSettings: {
                contentType: false
            },
            uploadExtraData: function (previewId, index) {   //额外参数 返回json数组
                return {
                    'id': commId
                };
            }
        }).on("filepredelete", function (jqXHR) {
            var abort = true;
            if (confirm("确定删除此图片?")) {
                abort = false;
            }
            return abort; // 您还可以发送任何数据/对象,你可以接收` filecustomerror
        })
            //.on('filebatchpreupload', function (event, data) {
            //var n = data.files.length, files = n > 1 ? n + ' files' : 'one file';
            //if (!window.confirm("确定上传选择的文件吗 ?")) {
            //    return {
            //        message: "上传失败!", // upload error message
            //        data: {} // any other data to send that can be referred in `filecustomerror`
            //    };
            //}
            //})
            .on('fileuploaded', function (event, data, id, index) {//上传成功之后的处理
            //自己打印data看看有哪些能用到的参数
                console.log(data);
                var fname = data.response[0].msg;
                if (index == data.files.length-1) {
                    location.href = '/Home/Test';
                }
                //alert(data.files.length);
            }).on('filebatchpreupload', function (event, data, id, index) {
                $('#kv-success-1').html('<h4>上传状态</h4><ul></ul>').hide();
            })
    }
    //下面四个方法是监控ajax表单提交的
    function onbegin() {
        console.log("开始");
    }

    function oncomplete(request, status) {
        console.log("成功");
    }

    function onfailure(request, error) {
        console.log("报错");
    }

//此处接收后台控制器返回的新增数据的ID,并触发bootstrap fileinput的上传方法
    function onsuccess(data) {
        var jsonObj = JSON.parse(data)
        console.log(jsonObj[0].error);
        commId = jsonObj[0].error;
        //触发上传方法
        $('#fileUpload').fileinput('upload');
    }
</script>

图片上传后台controller方法


        public ActionResult UploadFile()
        {
            var Mid="0";
            if (!Directory.Exists(Server.MapPath(attachFile)))//如果不存在就创建file文件夹
            {
                Directory.CreateDirectory(Server.MapPath(attachFile));
            }
            if (!string.IsNullOrEmpty(Request["id"]))
            {
                Mid = Request["id"];
            }
            string json = string.Empty;
            var image = Request.Files;
            if (image != null && image.Count > 0)
            {
                var _image = image[0];
                string _imageExt = System.IO.Path.GetExtension(_image.FileName).ToLower();
                string _imageName = DateTime.Now.ToString("yyyyMMddhhmmsssss") + _imageExt;
                //保存
                int iRdm = Rdm.Next(0, 100);
                _image.SaveAs(Server.MapPath(attachFile + iRdm.ToString()+ _imageName));
                tb_Enclosure model = new tb_Enclosure()
                {
                    Name = iRdm.ToString() + _imageName,
                    FileName = attachFile + iRdm.ToString() + _imageName,
                    Start = 1,
                    Modular = "相册",
                    Datetime = DateTime.Now,
                    ModularId=Convert.ToInt32(Mid)
                };
                tel.Add(model);
                tel.SaveChanges();
                json = "[{\"msg\":\"" + attachFile + iRdm.ToString() + _imageName + "\"}]";
            }
            else
            {
                json = "[{\"error\":\"文件保存失败\"}]";
            }
            return Content(json);
        }

到此图片上传结束,下章讲表单编辑以及图片删除,这是一个巨坑

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值