想使用ajaxfileupload,發(fā)現(xiàn)使用json的話無法取得返回值,找了好多個(gè)帖子,終于解決掉:
頁面代碼:
<input id="fileToUpload" type="file" name="fileToUpload" /> <input type="button" id="buttonUpload" onclick="return ajaxFileUpload();" value="Upload" /><img id="loading" src="/Content/loading.gif" style="display: none;" />
js代碼:
function ajaxFileUpload() { $("#loading") .ajaxStart(function () { $(this).show(); }) .ajaxComplete(function () { $(this).hide(); }); $.ajaxFileUpload({ url: '/File/Upload', secureuri: false, fileElementId: 'fileToUpload', dataType: 'json', success: function (data) { alert(data.msg); }, error: function (data) { alert("error"); } }); return false;}
FileController/Upload代碼:
[HttpPost]public JsonResult Upload(){ string filename = string.Empty; if (Request.Files["fileToUpload"] != null) { filename = Request.Files["fileToUpload"].FileName; Stream st = Request.Files["fileToUpload"].InputStream; } return this.Json(new { err = "", msg = "xxx.jpg" }, "text/x-json");}
其中重點(diǎn)就是: return Json(new { err = "", msg = "xxx.jpg" }, "text/x-json"); 需要給mvc中的json返回值指定contentType
聯(lián)系客服