解决IE浏览器中出现“ResourceinterpretedasDocumentbuttr。。
上传图⽚时,使⽤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
{
ie浏览器下载安装
//上传
//返回结果
return Json(new { UploadCode = 100, massege = "", sourceUrl = model.SourceImgUrl, bigUrl = model.BigImgUrl, thumbUrl = model.ThumbImgUrl });                        }
}
}
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浏览器了。