解決“Resource interpreted as Document but transferred with MIME type application/json”問題
阿新 • • 發佈:2017-06-19
ati str pos 單位 try transfer html subst clas
在上傳圖片時,使用ajax提交,返回的數據格式為json。在測試時發現IE瀏覽器中,上傳圖片後,沒有顯示圖片,而是彈出一個提示:是否保存UploadImg.json文件;而在其他瀏覽器中正常。
在Chrome中調試後發現,圖片上傳成功後,瀏覽器給出了一個警告:Resource interpreted as Document but transferred with MIME type application/json。
原來後臺代碼在返回json數據時,響應數據的ContentType默認為“application/json”,IE瀏覽器的新版本(IE10、IE11)會把該類型解釋為文件下載操作。
後臺代碼:
public JsonResult UploadImgToLocal() { var FileMaxSize = 10240; //文件大小,單位為K var model = new ImgUploadResult(); try { HttpPostedFile myFile = HttpContext.Current.Request.Files[0]; if (myFile != null) {string fileExtension = myFile.FileName.Substring(myFile.FileName.LastIndexOf(‘.‘)); if (!CheckValidExt(fileExtension)) { return Json(new { UploadCode = 104, massege = "文件格式錯誤" }); } else {if (myFile.ContentLength > FileMaxSize * 1024) { return Json(new { UploadCode = 105, massege = "文件過大" }); } else { //上傳 //返回結果 return Json(new { UploadCode = 100, massege = "", sourceUrl = model.SourceImgUrl, bigUrl = model.BigImgUrl, thumbUrl = model.ThumbImgUrl }); #endregion } catch { return Json(new { UploadCode = 101, massege = "上傳失敗" }); } } } } else { return Json(new { UploadCode = 102, massege = "請上傳文件" }); } } catch { return Json(new { UploadCode = 101, massege = "上傳失敗" }); } }
將代碼中的
return Json(new { UploadCode = 100, massege = "", sourceUrl = model.SourceImgUrl, bigUrl = model.BigImgUrl, thumbUrl = model.ThumbImgUrl });
改為:
JsonResult json = new JsonResult(); json.ContentType = "text/html"; json.Data = new { UploadCode = 100, massege = "", sourceUrl = model.SourceImgUrl, bigUrl = model.BigImgUrl, thumbUrl = model.ThumbImgUrl }; return json;
修改響應數據的ContentType類型後,返回的數據類型為json字符串,這樣就會兼容IE瀏覽器了。
解決“Resource interpreted as Document but transferred with MIME type application/json”問題