MVC 使用BeginForm + 文件上傳

form使用Controller MVCd的BeginForm生產html

public static MvcForm ExBeginForm(this AjaxHelper ajaxHelper, string areaName, string controllerName, string actionName, string onSuccess, string onBegin, object htmlAttributes) { string url = "/{0}/{1}/{2}"; url = string.Format(url, areaName, controllerName, actionName); return ajaxHelper.BeginForm(actionName, controllerName, new { area = areaName }, new AjaxOptions { HttpMethod = "Post", Url = url, OnSuccess = onSuccess, OnFailure = "onAjaxFailure", OnBegin = onBegin }, htmlAttributes ); }

model 定義接受屬性前端

public partial class PPF_Biz_NInvoice_Mod { public virtual HttpPostedFileBase FileImg { get; set; } }

view 中使用OnBegin結合 jquery.unobtrusive-ajax.min.js 文件進行提交處理,在生成的form標籤中默認加上data-ajax="true",但該屬性會致使頁面提交後臺獲取的FileImg始終是null,因此須要重寫該屬性.jquery

同時要加上enctype = "multipart/form-data"屬性。Mvc不識別 鏈接符「-」 使用「_」替代便可.ajax

@using (Ajax.ExBeginForm("Business/ChangShaZJ", "NInvoice", "Save", "onSaved", "onBegin", new { data_ajax = "false", enctype = "multipart/form-data" })) { @Html.HiddenFor(m => m.CustomerID) <div class="weui-cells weui-cells_form">
        <div class="weui-cell">
            <div class="weui-cell__hd">
                <label class="weui-label">標題</label>
            </div>
            <div class="weui-cell__bd"> @Html.TextBoxFor(m => m.Title, new Dictionary<string, object>() { { "class", "weui-input" } , }) </div>
        </div>
        <div class="weui-cell">
            <div class="weui-cell__hd">
                <label class="weui-label">發票編號</label>
            </div>
            <div class="weui-cell__bd"> @Html.TextBoxFor(m => m.No, new Dictionary<string, object>() { { "class", "weui-input" } , }) </div>
        </div>
        <div class="weui-cell">
            <div class="weui-cell__hd">
                <label class="weui-label">供應金額</label>
            </div>
            <div class="weui-cell__bd"> @Html.TextBoxFor(m => m.Account, new Dictionary<string, object>() { { "class", "weui-input" } , { "type", "number" } , { "pattern", "[0-9]*" } }) </div>
        </div>
        <div class="weui-cell">
            <div class="weui-cell__bd">
                <div class="weui-uploader">
                    <div class="weui-uploader__hd">
                        <p class="weui-uploader__title">圖片上傳</p>
                    </div>
                    <div class="weui-uploader__bd">
                        <ul class="weui-uploader__files" id="uploaderFiles">
                        </ul>
                        <div class="weui-uploader__input-box" id="uploaderAdd">
                            <input id="uploaderInput" class="weui-uploader__input" type="file" name="FileImg" accept="image/*" multiple />
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <br />
            
    <a id="btnSave" class="weui-btn weui-btn_primary" href="#" data-ajax="false" style="color: #fff; text-shadow: none; margin: 10px">保存</a> }

Bll 上傳文件json

public OperateResult UploadFile(string staticPath, HttpPostedFileBase file) { OperateResult rlt = new OperateResult(); rlt.isSuccess = true; try { var dateDir = DateTime.Now.ToString("yyyy-MM-dd"); var spath = staticPath + "/" + dateDir; rlt.model = spath + "/" + file.FileName; var path = HttpContext.Current.Server.MapPath(StaticPathEnum.UserResRoot + spath); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } string strPath = Path.Combine(path, file.FileName); file.SaveAs(strPath); } catch (Exception ex) { rlt.errorMesg = ex.ToString(); } return rlt; }

 可是這裏又回衍生一個新的問題,設置data_ajax = "false" 以後,form提交的onBegin以及onSuccess事件就無效了,因此提交的時候不能使用submit()方法提交,要使用ajaxSubmit()來提交.瀏覽器

同時頁面上面須要引用Jquery.form.js 文件app

$(function () { $.WY.bindMobileClick("#btnSave", function (sender) { var frm = $("#form0"); $.WY.formSubmitByFile(frm); }); });

文件提交通用方法,這裏的方法是寫在擴展中的經過擴展進行調用ui

getFunction: function (code) {
        var fn = window, parts = (code || "").split(".");
        while (fn && parts.length) { fn = fn[parts.shift()]; } if (typeof (fn) === "function") { return fn; } else { return null; } argNames.push(code); return Function.constructor.apply(null); }, formSubmitByFile: function (frm) { var data_ajax_begin = frm.attr("data-ajax-begin"); if (data_ajax_begin != "") { var fn = jQuery.WY.getFunction(data_ajax_begin); if (fn) { if (!fn.call(this, frm)) { return; } } } var action = frm.attr("data-ajax-url"); var method = frm.attr("data-ajax-method"); var onSaved = frm.attr("data-ajax-success"); var onAjaxFailure = frm.attr("data-ajax-failure"); frm.ajaxSubmit({ url: action, type: method, success: function (data) { var reg = /<pre.+?>(.+)<\/pre>/g; var result = data.match(reg); data = jQuery.parseJSON(RegExp.$1); var fn = jQuery.WY.getFunction(onSaved); fn.call(null, data); }, error: jQuery.WY.getFunction(onAjaxFailure) }); },

提交返回時還會出現序列化格式不對的問題,當後臺獲取到前臺傳來的文件時(例如上傳功能, 導入功能), 返回類型爲application/json, 這個時候響應到前端的JSON格式的數據格式多是:this

<pre style="word-wrap: break-word; white-space: pre-wrap;">{"JsonKey":"JsonValue"}</pre>url

這個是不一樣瀏覽器對返回數據處理的問題。可在前臺進行匹配取值,也能夠在後臺轉類型

相關文章
相關標籤/搜索