MVC中iframe无法加载Zip内MHT文件问题求助
解决iframe无法加载MHT文件(提示Attempted to load a multipart archive into an subframe)
问题背景
你遇到的情况是:存储在Zip压缩包中的MHT文件,直接访问MVC Action的URL时能正常显示,但通过iframe加载时失败,浏览器控制台抛出警告:Attempted to load a multipart archive into an subframe。
你的相关代码如下:
前端iframe代码
<iframe src="@Url.Action("LoadInstrucion","Pharmacy", new {id= Model.Instrukciya })"></iframe>
MVC控制器Action
public ActionResult LoadInstrucion(string id) { var bytes = InstructionsLoader.LoadInstrucion(id); return File(bytes, "multipart/related"); }
加载Zip中MHT的静态方法
public static byte[] LoadInstrucion(string zipFileName) { string zipfilePath = $@"{HttpContext.Current.Request.PhysicalApplicationPath}Content\inst\{zipFileName}.zip"; if (File.Exists(zipfilePath)) { using (var zipStream = new FileStream(zipfilePath, FileMode.Open)) using (var archive = new ZipArchive(zipStream, ZipArchiveMode.Read)) { if (archive.Entries.Count > 0) { var file = archive.Entries[0]; var stream = file.Open(); using (var ms = new MemoryStream()) { stream.CopyTo(ms); return ms.ToArray(); } } } } return new byte[0]; }
问题根源
这个警告的核心原因是浏览器限制在iframe子框架中直接渲染multipart/related类型的内容——而MHT文件的标准MIME类型正是multipart/related。当你直接访问Action URL时,浏览器会把它当作独立的顶级页面处理,自然能正常渲染;但iframe作为子框架,浏览器出于安全和渲染兼容性的考虑,会阻止这种加载行为。
解决方案
这里提供两种简单可行的方案,你可以根据场景选择:
方案1:后端返回包装HTML页面(推荐)
修改你的LoadInstrucion Action,不直接返回MHT字节流,而是返回一个包含object标签的HTML页面,让object标签来处理MHT内容,绕过浏览器的限制。
修改后的Action代码:
public ActionResult LoadInstrucion(string id) { var mhtBytes = InstructionsLoader.LoadInstrucion(id); if (mhtBytes.Length == 0) { return Content("MHT文件未找到"); } // 将MHT字节转换为Base64编码,嵌入到HTML中 string mhtBase64 = Convert.ToBase64String(mhtBytes); string wrapperHtml = $@" <html> <head> <style>body {{ margin: 0; padding: 0; }}</style> </head> <body> <object data=""data:multipart/related;base64,{mhtBase64}"" type=""multipart/related"" width=""100%"" height=""100%"" style=""border: none;""> 你的浏览器不支持嵌入MHT文件,请直接打开链接查看。 </object> </body> </html>"; return Content(wrapperHtml, "text/html"); }
修改后,iframe加载的是普通HTML页面,页面内的object标签会负责渲染MHT内容,完美避开浏览器的iframe限制。
方案2:前端通过Blob URL加载
如果不想修改后端代码,可以在前端通过AJAX获取MHT字节,创建Blob URL后赋值给iframe的src:
修改后的前端代码:
<iframe id="mhtFrame" style="width: 100%; height: 600px; border: none;"></iframe> <script> const mhtFrame = document.getElementById('mhtFrame'); // 发起请求获取MHT内容 fetch('@Url.Action("LoadInstrucion","Pharmacy", new {id= Model.Instrukciya })') .then(response => response.blob()) .then(blob => { // 创建Blob URL const blobUrl = URL.createObjectURL(blob); mhtFrame.src = blobUrl; // 页面卸载时释放Blob URL,避免内存泄漏 window.addEventListener('unload', () => URL.revokeObjectURL(blobUrl)); }) .catch(error => console.error('加载MHT文件失败:', error)); </script>
这种方式需要确保你的请求是同域的(或者后端配置了CORS允许跨域),通过Blob URL让iframe加载MHT,同样能绕过限制。
内容的提问来源于stack exchange,提问作者Oleksandr Khytrov
相关产品推荐
相关产品推荐

