解决IE浏览器中出现“Resource interpreted as Document but transferred with MIME type application/json”问题

在上传图片时,使用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 = ; //文件大小,单位为K
var model = new ImgUploadResult();
try
{
HttpPostedFile myFile = HttpContext.Current.Request.Files[];
if (myFile != null)
{
string fileExtension = myFile.FileName.Substring(myFile.FileName.LastIndexOf('.'));
if (!CheckValidExt(fileExtension))
{
return Json(new { UploadCode = , massege = "文件格式错误" });
}
else
{
if (myFile.ContentLength > FileMaxSize * )
{
return Json(new { UploadCode = , massege = "文件过大" });
}
else
{
//上传 //返回结果
return Json(new { UploadCode = , massege = "", sourceUrl = model.SourceImgUrl, bigUrl = model.BigImgUrl, thumbUrl = model.ThumbImgUrl });
}
}
}
else
{
return Json(new { UploadCode = , massege = "请上传文件" });
}
}
catch
{
return Json(new { UploadCode = , massege = "上传失败" });
}
}

将代码中的

return Json(new { UploadCode = , massege = "", sourceUrl = model.SourceImgUrl, bigUrl = model.BigImgUrl, thumbUrl = model.ThumbImgUrl });

改为:

JsonResult json = new JsonResult();
json.ContentType = "text/html";
json.Data = new { UploadCode = , massege = "", sourceUrl = model.SourceImgUrl, bigUrl = model.BigImgUrl, thumbUrl = model.ThumbImgUrl };
return json;

修改响应数据的ContentType类型后,返回的数据类型为json字符串,这样就会兼容IE浏览器了。

上一篇:java多线程&&并发面试108问(下)


下一篇:UESTC 1215 (思维题 旋转)