在与@roray 讨论之后-我在此处的菜单上添加了一个稍微不同的解决方案:) 首先:1. 不为此使用 base64 字符串(尽管可能)。2.我正在研究asp mvc 3.使用pdf.js的viewer.html查看器
因此,从服务器/控制器从 db 获取文件并返回咬合
public ActionResult LoadFile(int id)
{
var file = db.Files.Where(i => i.Id == id).FirstOrDefault();
return File(file.BinaryFile, MediaTypeNames.Application.Pdf, "Name.pdf");
}
在视图/html 中添加一个源未指定的 iframe (src="") 或者可以在页面加载事件中动态创建它。顺便说一句,我尝试使用 FF/Chrome/Edge/IE 11 的对象、嵌入和 iframe 并发现iframe 似乎始终如一地工作。虽然不喜欢 iframe:/
<iframe src="" name="printDoc" id="printDoc" width="800" height="1000" type="application/pdf"></iframe>
最后,在您的脚本标签中。这同样可以通过 Ajax 完成。基本上,一旦文档准备好调用服务器,以字节为单位获取文件,转换为 blob url,将 blob url附加到项目中 '/web/viewer.html?file=' 的相对位置并更新 src ="" 您的 iframe 的属性。
$(document).ready(function myfunction() {
var xhr = new XMLHttpRequest();
// works for EDGE/Chrome/FFox
xhr.open("GET", "/Documents/LoadFile/" + fileId, true);
xhr.responseType = "blob";
xhr.onload = function (e) {
if (this.status === 200) {
var blob = new Blob([this.response], { type: 'application/pdf' });
console.log('Not IE 11');
var url = window.URL.createObjectURL(blob);
_iFrame = document.querySelector("#printDoc");
_iFrame.setAttribute('src', '/web/viewer.html?file=' + url);
}
};
xhr.send();
});
这将打开嵌入在 iframe 中的 viewer.html 中的 pdf。MS Edge 可以正常工作,但不能通过地址栏作为查询参数发送 blob url,这显然受 FF/Chrome 支持。而且,这就是我选择这个选项的原因。
PS。IE 11 对我来说仍然没有希望,所以我使用了 var blob = new Blob([this.response], {type: 'application/pdf' });window.navigator.msSaveOrOpenBlob(blob, fileName);如果你找到请告诉我一种提高 IE 11 性能的方法