bootstraptable添加图片及显示图片,保存图片的物理路径

研究了两三个小时,解决了C#保存图片物理路径,并显示在bootstrap上的问题,终于解决了

前端代码如下:

@using System.Text
@using System.Web.Optimization
@using WarehouseManage.Model.Dto
@model Base_GoodsDto
@{
    ViewBag.Title = "添加物料";
    Layout = "~/Views/Shared/_Layout_Body.cshtml";
    var goodsTypelist = new List<SelectListItem>

{
new SelectListItem
{
Selected = true,
Text = "请选择",
Value = String.Empty
}
};
    var usingTypeList = new List<SelectListItem>
{
    new SelectListItem
{
Selected = true,
Text = "请选择",
Value = String.Empty
}
};
    var unitTypeList = new List<SelectListItem>
{
    new SelectListItem
{
Selected = true,
Text = "请选择",
Value = String.Empty
}
};
    var list = ViewBag.goodsTypeList as List<Base_GoodsTypeDto>;
    if (list?.Any() == true)
    {
        foreach (var item in list)
        {
            goodsTypelist.Add(
                new SelectListItem
                {
                    Text = item.Name,
                    Value = item.TypeID.ToString()
                });
        }
    }

    var list2 = ViewBag.usingTypeList as List<Base_UsingTypeDto>;
    if (list2?.Any() == true)
    {
        foreach (var item in list2)
        {
            usingTypeList.Add(
                new SelectListItem
                {
                    Text = item.Name,
                    Value = item.UsingTypeID.ToString()
                });
        }
    }

    var list3 = ViewBag.unitTypeList as List<Base_UnitDto>;
    if (list3?.Any() == true)
    {
        foreach (var item in list3)
        {
            unitTypeList.Add(
                new SelectListItem
                {
                    Text = item.Name,
                    Value = item.UnitID.ToString()
                });
        }
    }
}
@section StylesAfter{
    @Styles.Render("~/Template/Admin/jucheap/Css/SelectStyle")
    @Styles.Render("~/Template/Admin/jucheap/Css/Advance")
    @Styles.Render("~/Template/Admin/jucheap/Css/DataTable")
    @*<link href="~/Template/Admin/jucheap/css/select2.css" rel="stylesheet" />*@

}
@section Scripts{
    @Scripts.Render("~/JS/Admin/jucheap/Select")
    @Scripts.Render("~/JS/Admin/jucheap/Advance")

    @Scripts.Render("~/JS/Admin/jucheap/DataTable")
    <script>
        $("#submitForm").validate({
            submitHandler: jucheap.buttonLoading,
            rules: {
                GoodsCode: {
                    required: true,

                },
                Maximum: {
                    digits: true
                },
                Minimum: {
                    digits: true
                }
            },
            messages: {
                GoodsCode: {
                    required: "请输入物料编码"
                },
                Maximum: {
                    digits: "请输入正整数"
                },
                Minimum: {
                    digits: "请输入正整数"
                }
            }
        });

        $(function () {
            var Minimum;
            var Minimum;

            $("#Minimum").on("blur", function () {

                Minimum = $("#Minimum").val();
                Maximum = $("#Maximum").val();
                if (Minimum > Maximum) {

                    layer.msg("最小库存不能大于最大库存", { icon: 5, time: 5000 });
                }
            });

            $("#Maximum").on("blur", function () {

                Minimum = $("#Minimum").val();
                Maximum = $("#Maximum").val();
                if (Minimum > Maximum) {

                    layer.msg("最大库存不能小于最大库存", { icon: 5, time: 5000 });
                }
            });
            
            $("#imgsf").change(function () {
                $("#warning").html("");
                var filedx = 0;
                for (var i = 0, j = this.files.length; i < j; i++) {
                    $("#imgrq").html("");
                    $("#imgrq").append("<img  src=\"" + window.URL.createObjectURL(this.files[i]) + "\" width=\"100\" height=\"100\" />");
                }
                var file = getNameFromPath($(this).val());
                if (file != null) {
                    
                    var extension = file.substr((file.lastIndexOf('.') + 1));
                    switch (extension) {
                        case 'jpg':
                        case 'png':
                        case 'gif':
                        case 'jpeg':
                            fileTypeBool = false;
                            break;
                        default:
                           
                            fileTypeBool = true;
                    }
                }
                if (fileTypeBool) {
                    $("#warning").html("只能上传扩展名为jpg,png,gif,jpeg的文件!");
                    return false;
                }
                else {
                    var size = GetFileSize('ImagePath');
                    if (size > 4) {
                        fileSizeBool = true;
                        $("#warning").html("上传文件已经超过4兆!");
                    } else {
                        fileSizeBool = false;
                    }
                }
                
                
            });
        });
        function GetFileSize(fileid) {
            var fileSize = 0;
            fileSize = $("#" + fileid)[0].files[0].size;
            fileSize = fileSize / 1048576;
            return fileSize;
        }

        function getNameFromPath(strFilepath) {
            var objRE = new RegExp(/([^\/\\]+)$/);
            var strName = objRE.exec(strFilepath);

            if (strName == null) {
                return null;
            }
            else {
                return strName[0];
            }
        }

    </script>
}

<div class="row">
    <div class="col-xs-12">
        <section class="panel">
            <header class="panel-heading">
                添加物料
            </header>
            <div class="panel-body">
                <div class="form">
                    <form class="cmxform form-horizontal tasi-form" id="submitForm" method="POST" action="@Url.Action("Add")" novalidate="novalidate" enctype="multipart/form-data">

                        @Html.HiddenFor(item => item.GoodsID, new { @class = "form-control" })
                        <div class="form-group ">
                            @Html.LabelFor(item => item.GoodsCode, new { @class = "control-label col-xs-2" })
                            <div class="col-xs-4">
                                @Html.TextBoxFor(item => item.GoodsCode, new { @class = "form-control" })
                            </div>
                            @Html.LabelFor(item => item.SpecsName, new { @class = "control-label col-xs-2" })
                            <div class="col-xs-4">
                                @Html.TextBoxFor(item => item.SpecsName, new { @class = "form-control" })
                            </div>
                        </div>

                        <div class="form-group">
                            @Html.LabelFor(item => item.TypeID, new { @class = "control-label col-xs-2" })
                            <div class="col-xs-4">
                                @Html.DropDownListFor(item => item.TypeID, goodsTypelist, null, new { @class = "form-control", name = "TypeID" })
                            </div>
                            @Html.LabelFor(item => item.UsingTypeID, new { @class = "control-label col-xs-2" })
                            <div class="col-xs-4">
                                @Html.DropDownListFor(item => item.UsingTypeID, usingTypeList, null, new { @class = "form-control", name = "SpecsID" })
                            </div>
                        </div>

                        <div class="form-group">
                            @Html.LabelFor(item => item.UnitID, new { @class = "control-label col-xs-2" })
                            <div class="col-xs-4">
                                @Html.DropDownListFor(item => item.UnitID, unitTypeList, null, new { @class = "form-control", name = "UnitID" })
                            </div>
                            @Html.LabelFor(item => item.Price, new { @class = "control-label col-xs-2" })
                            <div class="col-xs-4">
                                @Html.TextBoxFor(item => item.Price, new { @class = "form-control" })
                            </div>
                        </div>

                        <div class="form-group ">
                            @Html.LabelFor(item => item.IsOld, new { @class = "control-label col-xs-2" })
                            <div class="col-xs-4">
                                <select class="form-control select2" id="IsOld" name="IsOld">
                                    <option value="" name="IsOld"></option>
                                    @{
                                        StringBuilder sb = new StringBuilder();
                                        sb.AppendFormat("<option value=\"{0}\" name=\"IsOld\">{1}</option>", 1, "是");
                                        sb.AppendFormat("<option value=\"{0}\" name=\"IsOld\">{1}</option>", 0, "否");
                                    }
                                    @(new MvcHtmlString(sb.ToString()));
                                </select>
                            </div>

                            @Html.LabelFor(item => item.IsKey, new { @class = "control-label col-xs-2" })
                            <div class="col-xs-4">
                                <select class="form-control select2" id="IsKey" name="IsKey">
                                    <option value="" name="IsKey"></option>
                                    @{
                                        StringBuilder sb2 = new StringBuilder();
                                        sb2.AppendFormat("<option value=\"{0}\" name=\"IsKey\">{1}</option>", 1, "是");
                                        sb2.AppendFormat("<option value=\"{0}\" name=\"IsKey\">{1}</option>", 0, "否");
                                    }
                                    @(new MvcHtmlString(sb2.ToString()));
                                </select>
                            </div>
                        </div>

                        <div class="form-group ">
                            @Html.LabelFor(item => item.IsBatch, new { @class = "control-label col-xs-2" })
                            <div class="col-xs-4">
                                <select class="form-control select2" id="IsBatch" name="IsBatch">
                                    <option value="" name="IsBatch"></option>
                                    @{
                                        StringBuilder sb3 = new StringBuilder();
                                        sb3.AppendFormat("<option value=\"{0}\" name=\"IsBatch\">{1}</option>", 1, "是");
                                        sb3.AppendFormat("<option value=\"{0}\" name=\"IsBatch\" selected=\"selected\">{1}</option>", 0, "否");
                                    }
                                    @(new MvcHtmlString(sb3.ToString()));
                                </select>
                            </div>

                            @Html.LabelFor(item => item.Maximum, new { @class = "control-label col-xs-2" })
                            <div class="col-xs-4">
                                @Html.TextBoxFor(item => item.Maximum, new { @class = "form-control" })
                            </div>
                        </div>

                        <div class="form-group ">
                            @Html.LabelFor(item => item.Minimum, new { @class = "control-label col-xs-2" })
                            <div class="col-xs-4">
                                @Html.TextBoxFor(item => item.Minimum, new { @class = "form-control" })
                            </div>
                            @Html.LabelFor(item => item.Remark, new { @class = "control-label col-xs-2" })
                            <div class="col-xs-4">
                                @Html.TextBoxFor(item => item.Remark, new { @class = "form-control" })
                            </div>
                        </div>

                        <div class="form-group ">
                            @Html.LabelFor(item => item.State, new { @class = "control-label col-xs-2" })
                            <div class="col-xs-4">
                                <select class="form-control select2" id="State" name="State">
                                    <option value="" name="State"></option>
                                    @{
                                        StringBuilder sb4 = new StringBuilder();
                                        sb4.AppendFormat("<option value=\"{0}\" name=\"State\" selected=\"selected\">{1}</option>", 1, "正常");
                                        sb4.AppendFormat("<option value=\"{0}\" name=\"State\">{1}</option>", 0, "禁用");
                                    }
                                    @(new MvcHtmlString(sb4.ToString()));
                                </select>
                            </div>
                            @* 上传图片 *@

                            <div class="col-xs-6">
                                @*The fileinput-button span is used to style the file input field as button*@
                                <span class="btn btn-success fileinput-button">
                                    <i class="glyphicon glyphicon-plus"></i>
                                    <span>添加图片</span>
                                    <input id="imgsf" type="file" name="ImagePath" />
                                </span>
                                @Html.ValidationMessageFor(item => item.ImagePath)
                                <span id="warning" style="color:red;font-size:large;"></span>
                            </div>

                                @*预览图片*@
                            <div id="imgrq" style="margin-left:20px;">

                            </div>

                        </div>
                        
                        <div class="form-group">
                            <div class="col-xs-offset-2 col-xs-10">
                                <button class="btn btn-success" type="submit">保存</button>
                                @*<button class="btn btn-default" type="button" onclick="jucheap.goback(this)">返回</button>*@
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </section>
    </div>
</div>  

注意:有几个坑

第一个坑:form表单提交的话加上enctype="multipart/form-data"

第二个坑:虽然我是用到了form但是在验证时,又使用了ajax提交,所以获取数据方式需要改变一下

jucheap.buttonLoading = function (form) {
    $(form).find("button[type='submit']:first").queue(function () {
        //form.submit();
        var form = $("#submitForm")[0];
        // Create an FormData object
        var data = new FormData(form);
        //var data = $(form).serializeArray()
        var url = $(form).attr("action");;
        $.ajax({
            url: url,
            enctype: 'multipart/form-data',
            type: 'post',
            data: data,
            processData: false, //Important, it prevent jQuery form transforming the data into a query string
            contentType: false,
            cache: false,
            dataType: 'json',
            //contentType: 'application/x-www-form-urlencoded',
            success: function (res) {

                if (res.flag) {
                    layer.msg("保存成功", { icon: 1, time: 1000 });
                    setTimeout(function () {
                        yui.layer_close3();
                    }, 500);
                    window.parent.$('#table_server').bootstrapTable('refresh');
                } else {
                    parent.layer.alert("保存失败:" + res.msg);
                }
            },
            error: function (e) {
                console.log(e);
            }
        });
        $(form).find("button[type='submit']:first").dequeue();
    });
}

controller层部分代码

HttpPostedFileBase postImage = Request.Files["ImagePath"];
                string filePath = postImage.FileName;
                string fileName = filePath.Substring(filePath.LastIndexOf("\\") + 1);
                string serverPath = Server.MapPath(@"\Images\Goods\") + fileName;
                string relativePath = @"/Images/Goods/" + fileName;
                postImage.SaveAs(serverPath);
                model.ImagePath = relativePath;
                model.UserID = HttpContext.User.Identity.Name;
                var goodsType = goodsTypeService.Get(x => x.TypeID == model.TypeID);
                model.GoodsName = goodsType.Name + "-" + model.SpecsName;
                goodsService.Update(model);
                return Json(new { flag = true });
以代码参考了很多网上的方法,不同的人可能遇到的情况不同,希望静下心来慢慢解决

猜你喜欢

转载自www.cnblogs.com/duhl1024/p/12014759.html
今日推荐